Html.EditorFor在MVC5.1中是否支持多于类?

时间:2014-03-17 20:55:10

标签: c# asp.net asp.net-mvc razor asp.net-mvc-5.1

如果不修改我的编辑器模板,是否可以将其他HTML属性传递到Html.EditorFor Helper扩展中?

该示例显示了传入的类:

@Html.EditorFor(model => model.information, new { htmlAttributes = new { @class = "form-control" }})

有很多潜在的场景,但我想用data-myvar="value"来装饰我的输入。当我尝试这个时,我得到编译器错误invalid anonymous type declaratory

@Html.EditorFor(model => model.information, new { htmlAttributes = new { @data-myvar="value" }})

另外,如果有可能我可以在课程之外传递此内容吗?即传入htmlattributes数组。除了发行说明之外,我很难找到任何文档。

John Galaway's article

1 个答案:

答案 0 :(得分:3)

确实如此,但由于.NET处理匿名类型(感谢Mark),您需要将短划线更改为下划线。此外,只有在Html属性字典中声明类时才需要@符号(因为类是保留字)。您可以在声明data-元素时将其关闭。

@Html.EditorFor(model => model.information, 
      new { htmlAttributes = new { data_myvar="value" }})

当帮助程序解析它时,实际上将在HTML中呈现破折号。

<input type="text" id="information" name="information" data-myvar="value"/>

要传入多个属性,只需用逗号

分隔值即可
@Html.EditorFor(model => model.information, 
      new { htmlAttributes = new { data_myvar="value", data_othervar = "something" }})