Set RadioButtonFor (), set by default in the Foreach loop

I have strange behavior using the @Html.RadioButtonForExtension method . I use the foreach loop to create a RadioButton list and a ternary operator. I am trying to establish someone who meets the condition for verification, but is always verified last. I was looking for a question about similars, but I'm not sure if I found something. And I do not want to create / use custom RadioButtonList.

Here is 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 the last one is always created, which checked, even if item.Default- false. So there is something

+4
source share
2

checked ( ), . HTML5. , checked, .

RadioButtonFor, checked htmlAttributes. - :

    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);
    }

( , , ) :

    @foreach (var item in Model.Entities)
    {
    <div>
             @Html.RadioButtonFor(m => item.Default, item.EntityId, new { /* other attributes go here */ }, item.Default)
    </div>
    }
+7

; ,

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

,

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

Source: https://habr.com/ru/post/1538690/


All Articles