Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting the class on a `Html.EditorFor`

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.

like image 381
balexandre Avatar asked Nov 02 '10 15:11

balexandre


People also ask

What does HTML EditorFor do?

The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property.

What is the difference between HTML textbox HTML TextBoxFor and HTML EditorFor?

TextBoxFor will always show the textbox element no matter which kind of property we are binding it with. But EditorFor is much flexible in this case as it decides which element will be more suitable to show the property.

How do I add an EditorFor style?

EditorFor does not allow for styling as there are no parameters for additional attributes. The reason for this is because the EditorFor doesn't always generate a single element as it can be overridden. To style a specific type of element you need to use the specific editor you want to use.


2 Answers

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\"")) %>
like image 51
marcind Avatar answered Oct 12 '22 07:10

marcind


In MCV 5.1 you can take advantage of htmlAttributes. Works like a charm...

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control", placeholder = "Enter your Name" } })
like image 39
Adam W Avatar answered Oct 12 '22 07:10

Adam W