MVC htmlAttributes and additionalViewData

本文探讨了ASP.NET MVC中@Html.EditorFor与@Html.TextBoxFor方法的使用差异,特别是在传递额外HTML属性如title时的表现不同。通过实例展示了如何正确设置htmlAttributes以确保所有期望的属性都能被正确输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值