ASP.NET MVC 3 Razor - Adding class to EditorFor

2020-01-25 04:25发布

I'm trying to add a class to an input.

This is not working:

@Html.EditorFor(x => x.Created, new { @class = "date" })

16条回答
一夜七次
2楼-- · 2020-01-25 04:49

I just needed to set the size of one textbox on one page. Coding attributes on the model and creating custom editor templates were overkill, so I just wrapped the @Html.EditorFor call with a span tag that called a class which specifies the size of the textbox.

CSS class declaration:

.SpaceAvailableSearch input
{
    width:25px;
}

View code:

<span class="SpaceAvailableSearch">@Html.EditorFor(model => model.SearchForm.SpaceAvailable)</span>
查看更多
淡お忘
3楼-- · 2020-01-25 04:51
@Html.EditorFor(m=>m.Created ...) 

does not allow any arguments to be passed in for the Text box

This is how you can apply attributes.

@Html.TextBoxFor(m=>m.Created, new { @class= "date", Name ="myName", id="myId" })
查看更多
放荡不羁爱自由
4楼-- · 2020-01-25 04:51

I used another solution using CSS attribute selectors to get what you need.

Indicate the HTML attribute you know and put in the relative style you want.

Like below:

input[type="date"]
{
     width: 150px;
}
查看更多
\"骚年 ilove
5楼-- · 2020-01-25 04:51

No need to create custom template for MVC 4. Use TextBox instead of EditFor here special html attributes are not supported, it is only supported from MVC 5. TextBox is should support for MVC 4, I don't know about other version.

@Html.TextBox("test", "", new { @id = "signupform", @class = "form-control", @role = "form",@placeholder="Name" })
查看更多
The star\"
6楼-- · 2020-01-25 04:54

You can use:

@Html.EditorFor(x => x.Created, new { htmlAttributes = new { @class = "date" } })

(At least with ASP.NET MVC 5, but I do not know how that was with ASP.NET MVC 3.)

查看更多
太酷不给撩
7楼-- · 2020-01-25 04:56

Adding a class to Html.EditorFor doesn't make sense as inside its template you could have many different tags. So you need to assign the class inside the editor template:

@Html.EditorFor(x => x.Created)

and in the custom template:

<div>
    @Html.TextBoxForModel(x => x.Created, new { @class = "date" })
</div>
查看更多
登录 后发表回答