是否可以在匿名类的成员名称中使用破折号 (-)?我主要对此感兴趣,以便与 asp.net mvc 一起使用以将自定义属性传递给 html-helpers,因为我希望我的 html 通过 html5-validation,这从 data- 开始。
无效的例子:
<%=Html.TextBoxFor(x => x.Something, new {data-animal = "pony"})%>
在成员名前加上 @ 也没有用。
更新:如果这不可能,是否有推荐的方法来做我想做的事?我目前的临时解决方案是像这样对整个事情添加一个替换:
<%=Html.TextBoxFor(x => x.Something, new {data___animal = "pony"}).Replace("___", "-")%>
但这很糟糕,因为它很难看,并且当 Model.Something
包含三个下划线时会中断。不呼。
最佳答案
刚刚在搜索同样的问题时发现了这篇文章。
我找到了这个链接: http://blogs.planetcloud.co.uk/mygreatdiscovery/post/Using-custom-data-attributes-in-ASPNET-MVC.aspx
它解决了这个问题。它提到了以下内容:
[...] 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;
}
关于c# - 匿名类成员中的破折号 (-),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2389041/