is it possible to use dash (-) in a member name of an anonymous class? I'm mainly interested in this to use with asp.net mvc to pass custom attributes to html-helpers, since I want my html to pass html5-validation, this starting with data-.
Exemple that doesn't work:
<%=Html.TextBoxFor(x => x.Something, new {data-animal = "pony"})%>
Putting a @ in front of the member name doesn't do the trick either.
Update: If this isn't possible, is there a recommended way todo what I want? My current temporary solution is to add a replace to the whole thing like this:
<%=Html.TextBoxFor(x => x.Something, new {data___animal = "pony"}).Replace("___", "-")%>
But that sucks, because it's ugly and will break when Model.Something
contains three underscores. Buhu.
Vincent Diamante (CC BY-SA 2.0) An anonymous type is a type that doesn't have a name. You can use an anonymous type to encapsulate a set of read-only properties inside a single unit — and you don't need to define the anonymous type beforehand.
In C#, you are allowed to create an anonymous type object with a new keyword without its class definition and var is used to hold the reference of the anonymous types. As shown in the below example, anony_object is an anonymous type object which contains three properties that are s_id, s_name, language.
Convert anonymous type(s) into a named typePress Ctrl+Shift+R and then choose Replace Anonymous Type with Named Class.
From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
Just found this post while searchching for the same problem.
I found this link: http://blogs.planetcloud.co.uk/mygreatdiscovery/post/Using-custom-data-attributes-in-ASPNET-MVC.aspx
It resolves the problem. It mentions the following:
[...] or better yet, just use code from ASP.NET MVC source:
public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes) { RouteValueDictionary result = new RouteValueDictionary(); if (htmlAttributes != null) { foreach (System.ComponentModel.PropertyDescriptor property in System.ComponentModel.TypeDescriptor.GetProperties(htmlAttributes)) { result.Add(property.Name.Replace('_', '-'), property.GetValue(htmlAttributes)); } } return result; }
Collecting the Asp-Mvc version specific ways to do data- here:
MVC 3+ : Use an underscore _ and it will be automatically replaced by mvc
MVC 1?,2: see @Jean-Francois answer, which points to this
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