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
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" : "")
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>
}