是否可以在匿名类的成员名称中使用短划线( - )?我主要感兴趣的是使用asp.net mvc将自定义属性传递给html-helpers,因为我希望我的html传递html5验证,这从data-开始.
例子不起作用:
<%=Html.TextBoxFor(x => x.Something, new {data-animal = "pony"})%>
Run Code Online (Sandbox Code Playgroud)
在成员名称前加上@也不起作用.
更新:如果这是不可能的,是否有推荐的方式来达到我的目的?我目前的临时解决方案是添加一个替换整个这样的事情:
<%=Html.TextBoxFor(x => x.Something, new {data___animal = "pony"}).Replace("___", "-")%>
Run Code Online (Sandbox Code Playgroud)
但这很糟糕,因为它很难看并且在Model.Something包含三个下划线时会破坏.Buhu.
Jea*_*ois 25
刚刚在搜索同一问题时找到了这篇文章.
我找到了这个链接:http: //blogs.planetcloud.co.uk/mygreatdiscovery/post/Using-custom-data-attributes-in-ASPNET-MVC.aspx
它解决了这个问题.它提到了以下内容:
[...]或者更好,只需使用ASP.NET MVC源代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
不能使用 - 作为任何标识符的一部分。 http://msdn.microsoft.com/en-us/library/aa664670(VS.71).aspx