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 do
Other than some minor improvements that could be made the helper looks fine:
ModelMetadata.FromLambdaExpression
twice with the same argumentsConvert.ToString()
.Here's the refactored version which takes into account those remarks:
public static IHtmlString RadioButtonWithLabelFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
TProperty value,
string labelText
)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
object currentValue = metadata.Model;
string property = metadata.PropertyName;
// Build the radio button html tag
var htmlRadio = new TagBuilder("input");
htmlRadio.GenerateId(property + value);
htmlRadio.Attributes["type"] = "radio";
htmlRadio.Attributes["name"] = property;
htmlRadio.Attributes["value"] = Convert.ToString(value);
if (object.Equals(currentValue, value))
{
htmlRadio.Attributes["checked"] = "checked";
}
// Build the label html tag
var label = new TagBuilder("label");
label.Attributes["for"] = htmlRadio.Attributes["id"];
label.SetInnerText(labelText);
// Return the concatenation of both tags
return new HtmlString(
htmlRadio.ToString(TagRenderMode.SelfClosing) + label.ToString()
);
}