9

如果我有类似的东西:

@Html.EditorFor(model => model.name)甚至:@Html.CheckBoxFor(m => m.RememberMe)

我将如何为它们添加一个 css 类或一个 id?我一直在阅读有关助手的内容,但我是否必须为每个元素制作一个助手?有没有简单的方法可以将类或 id 添加到剃刀表单元素?

4

3 回答 3

13

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" })
于 2013-04-17T14:01:54.073 回答
4

CheckboxFor 很容易,你可以这样做:

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

EditorFor 有点棘手,因为它不支持开箱即用。我的意思是您可以为每种类型创建一个模板,然后执行 TextBoxFor 添加 html 属性(与 CheckBoxFor 的语法相同)。您可能必须为您想要支持的每种类型执行此操作。

于 2013-04-17T14:04:17.253 回答
0

因为EditorFor不是特定于类型的,所以你不能在那些上使用它。

对于CheckBoxFor,您可以使用:

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

注意@前面,class因为这是 C# 中的保留关键字

于 2013-04-17T13:58:52.510 回答