匿名类成员中的短划线( - )

svi*_*nto 23 .net c# .net-3.5

是否可以在匿名类的成员名称中使用短划线( - )?我主要感兴趣的是使用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)

  • 从链接:"幸运的是,在ASP.NET MVC 3中添加了一个解决方案,以便您可以使用下划线而不是自动转换为连字符." (11认同)
  • 好吧,如果你想使用下划线,这很糟糕. (2认同)

µBi*_*Bio 14

收集Asp-Mvc版本特定的数据处理方法 - 这里:

MVC 3+:使用下划线_并将自动替换为mvc
MVC 1?,2:请参阅@ Jean-Francois答案,其中指向


And*_*rey 1

不能使用 - 作为任何标识符的一部分。 http://msdn.microsoft.com/en-us/library/aa664670(VS.71).aspx

  • 这个答案是正确的但不完整。有一个解决方法。请看我对这个问题的回答。 (3认同)