Addind css classes to razor elements

2019-02-22 02:53发布

In razor if I had something like:

@Html.EditorFor(model => model.name) or even: @Html.CheckBoxFor(m => m.RememberMe)

How would I add a css class or an id to them? I have been reading about helpers, but would I have to make a helper for every single element? is there no easy way to add a class or id to razor form elements?

3条回答
一夜七次
2楼-- · 2019-02-22 03:25

It's easy for CheckboxFor, you can do it like this:

@Html.CheckBoxFor(m => m.RememberMe, new { @class="your_class", @id="the_id" })

It's a bit trickier with EditorFor as it is NOT supported out of the box. What I mean is you can create a template for each type and then do a TextBoxFor adding html attributes (same syntax as with CheckBoxFor). You may have to do it for each type you want supported.

查看更多
做自己的国王
3楼-- · 2019-02-22 03:26

You cannot do that with the EditorFor helper simply because you don't know what template will be used. You could achieve it but you will need to write a custom editor template. For example this could be achieved by overriding the default editor template and taking into account the second parameter which represents an additional view data.

Here's an example of how such a custom editor template could look for string types (~/Views/Shared/EditorTemplates/string.cshtml):

@Html.TextBox(
    "", 
    ViewData.TemplateInfo.FormattedModelValue,
    ViewData
)

and then you could use it like that:

@Html.EditorFor(model => model.name, new { @class = "myclass" })

With the CheckBoxFor helper you could do that:

@Html.CheckBoxFor(m => m.RememberMe, new { @class = "myclass" })
查看更多
爷的心禁止访问
4楼-- · 2019-02-22 03:35

Because EditorFor isn't type-specific, you can't use it on those.

For CheckBoxFor, you can use:

@Html.CheckBoxFor(m => m.RememberMe, new { @class = "myClass", id = "myID" })

Note the @ before class because that's a reserved keyword in C#

查看更多
登录 后发表回答