Use exceptional char (minus) in property name of anonymous type
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 thedata-
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 in HtmlHelper.AnonymousObjectToHtmlAttributes
.
Eg: new { data_abc = "def" }
will be generated as data-abc="def"
.
This is not possible at all, unless you generate your own classes via Reflection.Emit. But you will still have to pass some 'dictionary' for this, so you might as well go for that.
Using C# 3 collection initializers should make it look a lot better.
I might miss something, but identifiers in C# are simply not allowed to contain a minus...
private int data-maxchars; // <- invalid
精彩评论