MVC htmlAttributes and additionalViewData

@Html.TextBoxFor(m => m.UserName, new { title = "ABC" })
// 输出结果为
<input data-val="true" data-val-required="The User name field is required." id="UserName" name="UserName" title="ABC" type="text" value="" />

@Html.EditorFor(m => m.UserName, new { title = "ABC" })
// 输出结果为
<input class="text-box single-line" data-val="true" data-val-required="The User name field is required." id="UserName" name="UserName" type="text" value="" />

很显然,第一个例子可以输出title属性,但第二个例子没有输出title属性。

原因是第一个例子的第二个参数为htmlAttributes,第二个例子中第二个参数为additionalViewData。

解决方案:

将htmlAttributes作为additionalViewData中的一个参数使用。如下:

@Html.EditorFor(model => model.EmailAddress,
                new { htmlAttributes = new { @class = "span4",
                                             maxlength = 128,
                                             required = true,
                                             placeholder = "Email Address",
                                             title = "A valid email address is required (i.e. user@domain.com)" } })
public static IDictionary<string, object> MergeHtmlAttributes<TModel>(this HtmlHelper<TModel> htmlHelper, object htmlAttributes)
{
    var attributes = htmlHelper.ViewData.ContainsKey("htmlAttributes")
                            ? HtmlHelper.AnonymousObjectToHtmlAttributes(htmlHelper.ViewData["htmlAttributes"])
                            : new RouteValueDictionary();

    if (htmlAttributes != null)
    {
        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
        {
            var key = property.Name.Replace('_', '-');
            if (!attributes.ContainsKey(key))
            {
                attributes.Add(key, property.GetValue(htmlAttributes));
            }
        }
    }

    return attributes;
}
 
原文地址:https://www.cnblogs.com/zqg123/p/5012063.html