在MVC 2中将CSS类添加到Html.EditorFor

我正在试图添加一个CSS类到文本框。 这是我的观点:

<%: Html.EditorFor(m => m.StartDate) %> 

我试着按照这个链接的说明做我的代码:

 <%: Html.EditorFor(m => m.StartDate, new { @class: "datepicker" }) %> 

但是我得到一个编译器错误说:

语法错误,','预计

我在这里做错了什么?

我会高度build议使用编辑模板 。 这绝对是编辑EditorFor的“正确”方式。

您可以通过两种不同的方式告诉模型属性使用编辑器模板。

第一个(最简单的)是为特定的数据types(例如DateTime )创build一个编辑器模板。
第二种方法是使用UIHint在DataAnnotations中声明性地设置它。

编辑
我还想补充一点,您应该在input字段中使用“date”types,以便即使禁用JavaScript,用户仍然可以看到本机dateselect器(仅在现代HTML5浏览器上有效)
<input id="meeting" type="date" value="2011-01-13"/>

随着MVC3,我不停地敲我的头,因为我无法得到这个工作。 我不想创build一个完整的EditorTemplate来添加一个类。

那么,而不是使用EditorFor,使用TextBoxFor ,当然等号如下所示:

 @Html.TextBoxFor(m=> m.ZipCode, new { @class = "zip" }) 

我想快速和肮脏的方式来做到这一点是在jQuery,是吗?

 $(document).ready(function () { $('#StartDate').addClass('datepicker'); }); 

理想情况下,你应该使用编辑模板。 我通过使用MvcHtmlString.Create()中的Editor Template来解决这个问题,它可以让你重build实际的HTML代码。 当然,你需要复制“类”部分中的所有内容,以使编辑器模板尽可能地有用。

我尝试了上面的许多build议,但是最终我决定了这一点,因为我认为它不那么复杂,它让我继续使用编辑器模板:

 @MvcHtmlString.Create(Html.EditorFor(m => m.StartDate).ToString().Replace("class=\"text-box single-line\"", "class=\"text-box single-line datepicker\"")) 

EditorFor不允许你设置HtmlProperties。 (IDictionary htmlAttributes)

这个链接解释了如何做到这一点:

http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates- 2D00 -ASP.Net-MVC-2.0-Beta_2D00_1.aspx

我知道这是一个古老的问题,但认为我可以贡献,所以在这里。 我有同样的问题,并希望避免编辑模板。 我只是想要一个通用的处理一切的解决scheme,这将允许我在视图中使用Html.EditorFor时指定html属性。

我真的很喜欢CIA的答案,但我扩大了一点,这样你就可以传递你需要的任何属性。 我创build了一个接受html属性的额外的Html.EditorFor方法:

 public static class EditorForExtentions { public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> 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); } } 

你可以像这样在视图中调用它

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

它使用正常的Html.EditorFor方法来获取htmlstring,然后注入所需的html属性。

我正在寻找一个解决scheme,将样式应用到@ HTML.EditorFor helper方法生成的特定框中。

问题是关于为@ HTML.EditorFor设置一个CSS类,但是对于任何想要编辑单个元素的样式的人来说 ,例如,你可以试试这个:

在我的模块中,我添加了一个基于助手生成的ID的样式:..

 <style> #EnrollmentInfo_Format { width:50px; font: normal 100% 'Lucida Grande',Tahoma,sans-serif; font-size: 11px; color: #2e6e9e; } </style> 

然后在我的页面(我在做一个局部视图):

 @Html.EditorFor(e => e.EnrollmentInfo.Format) 

这是一个非常简单的解决scheme:从"datepicker"删除双引号,并将其重新input到Visual Studio,它应该可以工作。

我有同样的问题。 我从网上复制/粘贴示例代码,代码有一个特殊types的引用引起","语法问题。 我知道这真的不明显。