The problem
I am trying to declare an anonymous type with a property named data-maxchars.
Because the minus is an operator it degrades (?) my desired property name into an operation and I get a compilation error: Invalid anonymous type member declarator.
I know I can escape reserved words using @, but I can’t figure out if there is any way to escape the minus.
object attributes = (object)new { @class = "foo" } // OK
The origin
The anonymous type is passed as an object argument to TextAreaExtensions.TextArea: <%= Html.TextArea(Model.Field.Id, val, rows, cols, attributes)%>. This generates an input with the delivered attributes.
I want to use JS progressive enhancement to limit the number of chars the user can insert.
So I am using the data- prefix on my attribute: http://ejohn.org/blog/html-5-data-attributes/
Alternatives
- While writing this I noticed there is an overload that takes an IDictionary instead of an object.
- I could write the input by hand.
- I could use a different prefix and ignore the standards. (Boo!)
But if there is a way to use the funny property name, I’d like to learn it.
Starting with ASP.NET MVC 3, you can use an underscore (
_) instead, it will be automatically be replaced by a-for HTML generation. The magic is done inHtmlHelper.AnonymousObjectToHtmlAttributes.Eg:
new { data_abc = "def" }will be generated asdata-abc="def".