c# - 匿名类成员中的破折号 (-)

标签 c# .net .net-3.5

是否可以在匿名类的成员名称中使用破折号 (-)?我主要对此感兴趣,以便与 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/

相关文章:

.net - Control.DestroyHandle 何时被调用?

c# - 如何为超线程/多核选择最佳线程数?

asp.net - 这两个有什么区别......?

c# - 如何找到控件的可见部分?

c# - Windows 8 中的单元测试 MediaElement (C#/XAML)

c# - 带 % 的参数化查询

c# - EF Core Update 会更新所有列,即使只有一列已更改

c# - 我可以将 JSON.NET 与我的商业应用程序一起分发吗?

c# - 将 Java Map<string, string> 从 XML 解析为 C# 对象

c# - 抽象类继承和数据契约