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">
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">
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)
@Html.EditorFor()
dynamically decides the type of control used based on the model element.
These customizations work with @Html.LabelFor()
of @Html.TextBoxFor()
. The following code has been testes and works properly.
Razor:
@Html.LabelFor(model => model.UserName, null, new { style = "display: inline;" })
@Html.TextBoxFor(model => model.UserName, null, new { style = "display: inline;" })
Generated HTML
<label style="display: inline;" for="UserName">
<input name="LastActivityDate" id="UserName" style="display: inline;" type="text" value=""/>
Please note that the second argument passed is null
, style is the third attribute. if using @Html.EditorFor()
is a must, then you have to use CSS class instead of style
@Html.EditorFor()
on MSDN
Note: The code has been tested with MVC4 and hopefully it is valid for MVC3 also
Instead of using
@Html.EditorFor(model => model.UserId)
Use
@Html.TextBoxFor(model => model.UserId, new { @Value = "Prabhat" })
For what it's worth I had this same problem. I resolved it by using a slightly different version of Narenda V's solution.
I created a class like this: (note - min-width instead of width)
.userName { min-width:40em; }
then in my view:
@Html.EditorFor(model => model.UserName, new { @class = "userName" })
When I did not use min-width, but width, it did not work. Bob
If you need to use EditorFor and not TextBoxFor and have multiple editors on the page, but only need to change the width of specific ones... The easiest what is to add a css style to the class ID as such:
<style type="text/css">
input#UserName { width: 100px; }
</style>
You can create a style class in .css like
.userName
{
width: 150px;
}
Style can be appilied with html class attribute.
@Html.EditorFor(model => model.UserName, new { @class = "userName" })