当属性为"data-*"时,如何从对象htmlAttributes中获取有效的HTML属性

Sim*_*tes 4 c# asp.net-mvc html-helper

我想将htmlAttributes作为一个object类似的方法传递给...

     foo.HtmlAttributes(new { data_bind = "foo"});
Run Code Online (Sandbox Code Playgroud)

在所有的MVC HtmlHelpers中,我使用下划线作为连字符,这将输出有效的html "data-bind"

在幕后,这是根据以下问题进行的:

如何从对象HtmlAttributes中获取值

将对象传递给HTML属性

    public virtual void HtmlAttributes(object htmlAttributes)
    {
       this.Attributes = new RouteValueDictionary(htmlAttributes);
    }
Run Code Online (Sandbox Code Playgroud)

后来这将被称为:

    internal virtual void ApplyConfiguration(TagBuilder tag)
    {
            tag.MergeAttributes(this.Attributes);
    }
Run Code Online (Sandbox Code Playgroud)

但是这会输出:

<div data_bind="foo"></div>
Run Code Online (Sandbox Code Playgroud)

如何输出有效的HTML?

更新 感谢Zabavsky ......

public virtual void HtmlAttributes(object htmlAttributes)
{      
        this.Attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
}
Run Code Online (Sandbox Code Playgroud)

Zab*_*sky 6

HtmlHelperclass具有AnonymousObjectToHtmlAttributes方法,该方法有助于创建符合HTML5的标记.该方法用连字符替换下划线字符.