Custom helper for generating html tags for radio button and associated label

前端 未结 1 677
我在风中等你
我在风中等你 2021-01-24 17:29

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

相关标签:
1条回答
  • 2021-01-24 18:20

    Other than some minor improvements that could be made the helper looks fine:

    • You don't need to call ModelMetadata.FromLambdaExpression twice with the same arguments
    • In order to generate the id you are concatenating the property name with the value but this value could contain any characters while an id in HTML allows only certain characters. You need to sanitize it.
    • You are casting both the value and currentValue to strings which might fail if the helper is used on some other property type. In this case either make the helper work only with string properties by reflecting on the helper signature or use Convert.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()
        );
    }
    
    0 讨论(0)
提交回复
热议问题