mvc 3 Html.EditorFor add html attribute not work

58,975

Solution 1

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" })

Solution 2

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

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

@Html.EditorFor(model => model.UserName)

Solution 3

@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

Solution 4

Instead of using
@Html.EditorFor(model => model.UserId)
Use
@Html.TextBoxFor(model => model.UserId, new { @Value = "Prabhat" })

Share:
58,975
Hryhorii
Author by

Hryhorii

I like Japanese and Japan culture. I work now how free lance. I'm .NET Developer.

Updated on October 08, 2020

Comments

  • Hryhorii
    Hryhorii over 3 years

    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">
    
  • Hryhorii
    Hryhorii almost 13 years
    Add new class style not help. Because in result not add
  • Hryhorii
    Hryhorii almost 13 years
    This is stupid. Why impose such a developer. Before everything worked :(
  • Narendra V
    Narendra V almost 13 years
    try @Html.TextBoxFor(model => model.UserName, new { @class = "userName" })