将rassor元素添加到razor元素中
剃刀如果我有类似的东西:
@Html.EditorFor(model => model.name)
或甚至: @Html.CheckBoxFor(m => m.RememberMe)
我如何向他们添加css类或id? 我一直在阅读帮助者,但我是否必须为每一个元素做一个帮手? 有没有简单的方法来添加类或id到剃刀表单元素?
你不能仅仅因为你不知道将使用什么模板而使用EditorFor
帮助器。 您可以实现它,但您需要编写自定义编辑器模板。 例如,这可以通过覆盖default editor template
并考虑表示附加视图数据的第二参数来实现。
下面是一个示例,说明这样的自定义编辑器模板如何查找字符串类型( ~/Views/Shared/EditorTemplates/string.cshtml
):
@Html.TextBox( "", ViewData.TemplateInfo.FormattedModelValue, ViewData )
然后你就可以这样使用它:
@Html.EditorFor(model => model.name, new { @class = "myclass" })
使用CheckBoxFor助手,您可以这样做:
@Html.CheckBoxFor(m => m.RememberMe, new { @class = "myclass" })
CheckboxFor很容易,你可以这样做:
@Html.CheckBoxFor(m => m.RememberMe, new { @class="your_class", @id="the_id" })
使用EditorFor有点棘手,因为它不支持开箱即用。 我的意思是你可以为每种类型创建一个模板,然后做一个TextBoxFor添加html属性(与CheckBoxFor相同的语法)。 您可能必须为要支持的每种类型执行此操作。
因为EditorFor
不是特定于类型的,所以不能在那些上使用它。
对于CheckBoxFor
,您可以使用:
@Html.CheckBoxFor(m => m.RememberMe, new { @class = "myClass", id = "myID" })
注意@
before class
因为这是C#中的保留关键字