Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 230
ANeves Avatar asked Aug 15 '11 11:08

ANeves


2 Answers

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".

like image 175
Julien Lebosquain Avatar answered Sep 23 '22 04:09

Julien Lebosquain


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.

like image 37
leppie Avatar answered Sep 22 '22 04:09

leppie