Create CheckboxFor MVC helper with title attribute from model description

后端 未结 2 1550
陌清茗
陌清茗 2021-01-20 07:26

I\'ve created a text box helper to add a title (tooltip) taken from the description attribute for the field in a model:

 public static MvcHtmlString TextBoxF         


        
2条回答
  •  被撕碎了的回忆
    2021-01-20 07:48

    You current implementations are not taking into account model binding and ModelState, do not generate the attributes necessary for unobtrusive validation and can generate incorrect id attributes.

    Make use of the existing html helper methods in your own helpers so you generate the correct html. Your TextBoxForWithTitle() method need only be

    public static MvcHtmlString TextBoxForWithTitle(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes = null)
    {
        var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        IDictionary attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        if (!string.IsNullOrEmpty(metaData.Description))
        {
            attributes.Add("title", metaData.Description);
        }
        return htmlHelper.TextBoxFor(expression, attributes);
    }
    

    and similarly the CheckBoxForWithTitle() would be the same except

    return htmlHelper.CheckBoxFor(expression, attributes);
    

    Side note: To see how the existing helpers actually work, you can view the source code here

提交回复
热议问题