Set a RadioButtonFor() checked by default within a

2019-02-14 16:03发布

I have a weird behavior using @Html.RadioButtonFor Extension Method. I am using a foreach loop to create a list of RadioButton and By ternary operator. I am trying to set the one who respect the condition to checked but It is always the last who is checked. I searched similars question but I am not sure to have found something. And I don't want to create/use a custom RadioButtonList.

Here my code in my View:

@foreach (var item in Model.Entities)
        {
        <div>
                 @Html.RadioButtonFor(m => item.Default, item.EntityId,
                       new { @checked = item.Default ? "checked" : "" })//item.Default is a bool and there is only one set to True 
        </div>
        }

But In my browser it is always the last created which is checked even if item.Default is false. So is there something

2条回答
乱世女痞
2楼-- · 2019-02-14 16:38

If the checked attribute is present (no matter what it's actual value is), the browsers see the button as checked. This is HTML5 behavior. I'm guessing all radiobuttons have the checked attribute defined and the browser will select the last button to be the final selected one.

My solution is to create a custom RadioButtonFor extension method, which accepts a boolean for the checked-state and depending on the value add the checked attribute to the htmlAttributes dictionary. Something like so:

    public static MvcHtmlString RadioButtonFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object value, object htmlAttributes, bool checkedState)
    {
        var htmlAttributeDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

        if (checkedState)
        {
            htmlAttributeDictionary.Add("checked", "checked");
        }

        return htmlHelper.RadioButtonFor(expression, value, htmlAttributeDictionary);
    }

You can then use that method in your view (don't forget to add the namespace where you created the extension method and put it in the config) like so:

    @foreach (var item in Model.Entities)
    {
    <div>
             @Html.RadioButtonFor(m => item.Default, item.EntityId, new { /* other attributes go here */ }, item.Default)
    </div>
    }
查看更多
我命由我不由天
3楼-- · 2019-02-14 17:02

The precedence of operators is causing the problem here; as equality comes before comparison, the phrase will be evaluated as

(@checked = item.Default) ? "checked" : ""

whereas you want it to be

@checked = (item.Default ? "checked" : "")
查看更多
登录 后发表回答