mvc 3 Html.EditorFor add html attribute not work

2019-03-23 05:11发布

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

7条回答
Anthone
2楼-- · 2019-03-23 06:03

@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

查看更多
登录 后发表回答