mvc4 html.editorfor 样式,c# - Add css class to Html.EditorFor in MVC 2 - Stack Overflow

I know this is an old question but thought I could contribute so here goes. I had the same problem and wanted to avoid making Editor Templates. I just wanted a generic handle everything solution that would allow me to specify html attributes when using Html.EditorFor in a view.

I really liked CIAs answer, but I expanded on it a bit so that you can pass in any attributes you need. I created an extra Html.EditorFor method that accepts html attributes:-

public static class EditorForExtentions

{

public static MvcHtmlString EditorFor(this HtmlHelper html, Expression> expression, Object htmlAttributes, bool extendAttributes)

{

string value = html.EditorFor(expression).ToString();

PropertyInfo[] properties = htmlAttributes.GetType().GetProperties();

foreach (PropertyInfo info in properties)

{

int index = value.ToLower().IndexOf(info.Name.ToLower() + "=");

if (index < 0)

value = value.Insert(value.Length - (value.EndsWith("/>") ? 2 : 1), info.Name.ToLower() + "=\"" + info.GetValue(htmlAttributes, null) + "\"");

else if (extendAttributes)

value = value.Insert(index + info.Name.Length + 2, info.GetValue(htmlAttributes, null) + " ");

}

return MvcHtmlString.Create(value);

}

}

You can call it in a view like this

m.StartDate, new { @class = "datepicker" }, true)%>

It uses the normal Html.EditorFor method to get the html string, then injects the html attributes needed.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值