在`Html.EditorFor`上覆盖类

bal*_*dre 13 textinput class-attributes asp.net-mvc-2

默认情况下用

<%: Html.EditorFor(m => m.ConfirmationHeadline) %>
Run Code Online (Sandbox Code Playgroud)

输出是:

 <input type="text" value="" 
        name="ConfirmationHeadline" id="ConfirmationHeadline" 
        class="text-box single-line">
Run Code Online (Sandbox Code Playgroud)

如您所见,输入已附加class属性.嗯,这不应该是一个问题,只需使用

<%: Html.EditorFor(m => m.ConfirmationHeadline, new { @class="span-11 last"}) %>
Run Code Online (Sandbox Code Playgroud)

应该工作...... 错误......不!

这将输出完全相同的代码!

虽然,工作正常 Html.TextAreaFor()

如何从中删除该类text-box single-line,以便可以附加我自己的类?我应该编辑的任何T4模板?

谢谢你的帮助.

mar*_*ind 11

通过该EditorFor方法使用内置编辑器模板时,无法自定义发出的类属性的值.它对类值进行硬编码(更多信息请访问:http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html)

您有两种选择:

  1. 编写自己的支持额外功能的自定义模板.有关详细信息,请查看此处:http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html

  2. 处理EditorFor方法的输出:

 <%: new HtmlString(Html.EditorFor(m=>m.ConfirmationHeadline).ToString()
        .Replace("class=\"text-box single-line\"", 
                 "class=\"text-box single-line span-11 last\"")) %>
Run Code Online (Sandbox Code Playgroud)


Ada*_*m W 5

在MCV 5.1中,您可以利用htmlAttributes.奇迹般有效...

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control", placeholder = "Enter your Name" } })
Run Code Online (Sandbox Code Playgroud)