This functionality is, surprisingly enough, provided by the RouteValueDictionary
class:
IDictionary<string, object> htmlAttributes = new RouteValueDictionary(attrs);
You can then use this dictionary in conjunction with a TagBuilder
, which you will probably be using anyway:
var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.ToString(TagRenderMode.Normal);
You can see this done in the ASP.NET MVC source code itself; one of the simpler examples is in TextAreaExtensions.cs.
EDIT:
In order to properly convert "data_attr" to "data-attr", use the AnonymousObjectToHtmlAttributes
static method.
IDictionary<string, object> htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attrs);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…