1

Without modifying my Editor Templates, is it possible to pass other HTML attributes into the Html.EditorFor Helper extension?

The example shows a class being passed in:

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

There are many potential scenarios but I want to decorate my input with a data-myvar="value". When I try this I get compiler errors invalid anonymous type declaratory.

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

Additionally if it is possible can I pass this in in addition to a class? i.e. pass in an array of htmlattributes. I'm struggling to find any documentation apart from the release notes.

John Galaway's article

4

1 回答 1

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" }})
于 2014-03-17T20:59:50.830 回答