Overwriting the class on a `Html.EditorFor`

balexandre picture balexandre · Nov 2, 2010 · Viewed 15.1k times · Source

by the default with

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

the output is:

 <input type="text" value="" 
        name="ConfirmationHeadline" id="ConfirmationHeadline" 
        class="text-box single-line">

As you can see, the input appends already a class attribute. Well, this should not be a problem, just use

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

and should work... err... nope!

this will output the exact same code!

though, works fine with Html.TextAreaFor()

How can I remove the class text-box single-line from ever appear so my own classes could be appended? any T4 template I should edited?

Thank you for all the help.

Answer

marcind picture marcind · Nov 2, 2010

There is no way to customize the value of the emitted class attribute when using built-in editor templates via the EditorFor method. It hard-codes the class value (more info available here: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html)

You have two options:

  1. Write your own custom template that supports the extra functionality. Have a look here for more details: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html

  2. Process the output of the EditorFor method:

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