Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc 3 Html.EditorFor add html attribute not work

Tags:

I try add html attribute for EditorFor

 @Html.EditorFor(model => model.UserName, new { style = "width: 100px" })

But any way I get

<input id="UserName" class="text-box single-line" type="text" value="" name="UserName">
like image 331
Hryhorii Avatar asked Jul 01 '11 16:07

Hryhorii


People also ask

How does HTML EditorFor work?

Simply put, the Html. EditorFor method allows the developer to retain control over the display of form elements by data type (ie. string, boolean, int…etc) or model attribute at a global level rather than at an individual view level. This allows for cleaner ASP markup and easily scalable form controls.

What is HTML EditorFor in MVC?

ASP.NET MVC includes the method that generates HTML input elements based on the datatype. 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?

Show activity on this post. TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control. EditorFor: This control is bit smart.

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

EditorFor is going to overwrite those attributes. See Html attributes for EditorFor() in ASP.NET MVC for workarounds.

If all you need to change is the display of the width, and you're not relying on any Editor Templates then the easiest fix is to use TextBoxFor instead

 @Html.TextBoxFor(model => model.UserName, new { style = "width: 100px" })
like image 83
DMulligan Avatar answered Oct 11 '22 07:10

DMulligan


I had the same issue and this solved it...

<style type="text/css">
#UserName { 
    width: 100px; 
}
</style>

@Html.EditorFor(model => model.UserName)
like image 30
BGTechie Avatar answered Oct 11 '22 07:10

BGTechie