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条回答
欢心
2楼-- · 2019-03-23 05:41

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" })
查看更多
贪生不怕死
3楼-- · 2019-03-23 05:45

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

查看更多
\"骚年 ilove
4楼-- · 2019-03-23 05:46

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>
查看更多
Rolldiameter
5楼-- · 2019-03-23 05:52

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

查看更多
祖国的老花朵
6楼-- · 2019-03-23 05:56

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" })
查看更多
孤傲高冷的网名
7楼-- · 2019-03-23 06:00

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

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

@Html.EditorFor(model => model.UserName)
查看更多
登录 后发表回答