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

Tim
  • 7,401
  • 13
  • 61
  • 102

1 Answers1

3

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" }})
Tommy
  • 39,592
  • 10
  • 90
  • 121
  • awesome thanks, how do i pass in more than one attribute? i.e. an array? – Tim Mar 17 '14 at 21:01
  • 2
    Not strictly because of razor, but of any anonymous type. The dash is not a valid character in any identifier – Mark Peters Mar 17 '14 at 21:01
  • @MarkPeters - Updated addressing your comment as well – Tommy Mar 17 '14 at 21:03
  • cheers @Tommy that works It might just be me but im finding with the new agile release methods of the asp.net team there seems to be less documentation. Barring a few examples. Asp.Net Identity is the perfect example in this i found. – Tim Mar 17 '14 at 21:05