Set a RadioButtonFor() checked by default within a Foreach loop

前端 未结 2 463
旧巷少年郎
旧巷少年郎 2021-01-06 07:41

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 try

相关标签:
2条回答
  • 2021-01-06 08:12

    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" : "")
    
    0 讨论(0)
  • 2021-01-06 08:23

    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>
        }
    
    0 讨论(0)
提交回复
热议问题