可以在匿名类的成员名中使用破折号(-)吗?我主要感兴趣的是在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包含三个下划线时会中断。布胡。
发布于 2010-03-06 02:35:17
不能使用-作为任何标识符的一部分。http://msdn.microsoft.com/en-us/library/aa664670(VS.71).aspx
发布于 2011-04-08 23:41:17
我在搜索同样的问题时发现了这篇文章。
我找到了这个链接: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;
}发布于 2012-10-09 02:45:33
收集Asp-Mvc版本的具体方法做数据-在这里:
MVC 3+:使用下划线_,它将自动被mvc替换
MVC1?,2:请参阅@Jean-Francois答案,它指向this
https://stackoverflow.com/questions/2389041
复制相似问题