问题
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
回答1:
It does, but because of how .NET handles anonymous types (thanks Mark), you need to change the dash to an underscore. Also the @
symbol is only needed when you are declaring the class in the Html attributes dictionary (since class is a reserved word). You can leave that off when declaring data-
elements.
@Html.EditorFor(model => model.information,
new { htmlAttributes = new { data_myvar="value" }})
When this is parsed by the helper, a dash will actually be rendered out in the HTML.
<input type="text" id="information" name="information" data-myvar="value"/>
To pass in multiple attributes, just separate the values by a comma
@Html.EditorFor(model => model.information,
new { htmlAttributes = new { data_myvar="value", data_othervar = "something" }})
来源:https://stackoverflow.com/questions/22465172/does-html-editorfor-support-more-than-class-in-mvc5-1