MVC Razor Radio Button

2019-02-05 10:44发布

In partial view I work with textboxes like this.

@model Dictionary<string, string>
@Html.TextBox("XYZ", @Model["XYZ"])

How can i generate radiobuttons, and get the desired value in the form collection as YES/NO True/False) ? Currently i am getting null for "ABC" if i select any value for the below.

   <label>@Html.RadioButton("ABC", @Model["ABC"])Yes</label>
   <label>@Html.RadioButton("ABC", @Model["ABC"])No</label>

Controller

        public int Create(int Id, Dictionary<string, string> formValues)
        {
         //Something Something
        }

11条回答
Emotional °昔
2楼-- · 2019-02-05 11:08

Simply :

   <label>@Html.RadioButton("ABC", True)Yes</label>
   <label>@Html.RadioButton("ABC", False)No</label>

But you should always use strongly typed model as suggested by cacho.

查看更多
仙女界的扛把子
3楼-- · 2019-02-05 11:11
<div class="col-md-10">
    Male:   @Html.RadioButton("Gender", "Male")
    Female: @Html.RadioButton("Gender", "Female")
</div>                         
查看更多
三岁会撩人
4楼-- · 2019-02-05 11:16

This works for me.

@{ var dic = new Dictionary<string, string>() { { "checked", "" } }; }
@Html.RadioButtonFor(_ => _.BoolProperty, true, (@Model.BoolProperty)? dic: null) Yes
@Html.RadioButtonFor(_ => _.BoolProperty, false, (!@Model.HomeAddress.PreferredMail)? dic: null) No
查看更多
趁早两清
5楼-- · 2019-02-05 11:19

In order to do this for multiple items do something like:

foreach (var item in Model)
{
    @Html.RadioButtonFor(m => m.item, "Yes") @:Yes
    @Html.RadioButtonFor(m => m.item, "No") @:No
}
查看更多
Summer. ? 凉城
6楼-- · 2019-02-05 11:20

I wanted to share one way to do the radio button (and entire HTML form) without using the @Html.RadioButtonFor helper, although I think @Html.RadioButtonFor is probably the better and newer way (for one thing, it's strongly typed, so is closely linked to theModelProperty). Nevertheless, here's an old-fashioned, different way you can do it:

    <form asp-action="myActionMethod" method="post">
        <h3>Do you like pizza?</h3>
        <div class="checkbox">
            <label>
                <input asp-for="likesPizza"/> Yes
            </label>
        </div>
    </form>

This code can go in a myView.cshtml file, and also uses classes to get the radio-button (checkbox) formatting.

查看更多
登录 后发表回答