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 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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With