4

I would like to pass htmlAttributes as an object to a method like so...

     foo.HtmlAttributes(new { data_bind = "foo"});

In all the MVC HtmlHelpers I have used the underscore as a hyphen, this would output valid html "data-bind"

Under the hood this is what is going on as per the following questions:

How to get values out of object HtmlAttributes

Passing an object to HTML attributes

    public virtual void HtmlAttributes(object htmlAttributes)
    {
       this.Attributes = new RouteValueDictionary(htmlAttributes);
    }

And then Latter this will be called:

    internal virtual void ApplyConfiguration(TagBuilder tag)
    {
            tag.MergeAttributes(this.Attributes);
    }

However this would output:

<div data_bind="foo"></div>

What can I do to output valid HTML?

UPDATE Thanks to Zabavsky...

public virtual void HtmlAttributes(object htmlAttributes)
{      
        this.Attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
}
Community
  • 1
  • 1
SimonGates
  • 5,961
  • 4
  • 40
  • 52
  • 1
    You can use [HtmlHelper.AnonymousObjectToHtmlAttributes Method](http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.anonymousobjecttohtmlattributes(v=vs.108).aspx). It replaces underscore characters with hyphens. – Zabavsky May 22 '13 at 12:23
  • Thanks, add an answer and I will accept. – SimonGates May 22 '13 at 12:27

1 Answers1

6

HtmlHelper class has AnonymousObjectToHtmlAttributes method, which helps to create markup that is compliant with HTML5. The method replaces underscore characters with hyphens.

Zabavsky
  • 13,340
  • 8
  • 54
  • 79