I was searching for a solution about radio buttons and associated labels. I like the way we can select each radio button by clicking on the label associated. By default, this doesn’t work very well. I mean the labels are not correctly associated with radio buttons.
Example: let’s say we have a property named Revoked with possible values Yes/No. We would like to use radio buttons to let the user choose the value.
The problem: when html tags are generated from MVC (Html.LabelFor, Html.RadioButtonFor), the ID of both radio buttons (Yes/No) are the same. Thus it is impossible to associate each label with the corresponding radio button.
The solution: I created my own custom helper for generating html tags with correct and unique ID.
Here is my helper:
public static MvcHtmlString RadioButtonWithLabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object labelText)
{
object currentValue = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model;
string property = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).PropertyName;
// Build the radio button html tag
TagBuilder htmlRadio = new TagBuilder("input");
htmlRadio.MergeAttribute("type", "radio");
htmlRadio.MergeAttribute("id", property + value);
htmlRadio.MergeAttribute("name", property);
htmlRadio.MergeAttribute("value", (string)value);
if (currentValue != null && value.ToString() == currentValue.ToString()) htmlRadio.MergeAttribute("checked", "checked");
// Build the label html tag
TagBuilder htmlLabel = new TagBuilder("label");
htmlLabel.MergeAttribute("for", property + value);
htmlLabel.SetInnerText((string)labelText);
// Return the concatenation of both tags
return MvcHtmlString.Create(htmlRadio.ToString(TagRenderMode.SelfClosing) + htmlLabel.ToString());
}
It works but I need advise. What do you think? Is it efficient? I’m still new to the world of ASP.NET MVC so any help is greatly appreciated.
Thanks.
Other than some minor improvements that could be made the helper looks fine:
ModelMetadata.FromLambdaExpressiontwice with the same argumentsConvert.ToString().Here’s the refactored version which takes into account those remarks: