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">
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.
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.
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.
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.
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" })
I had the same issue and this solved it...
<style type="text/css">
#UserName {
width: 100px;
}
</style>
@Html.EditorFor(model => model.UserName)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With