Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to pass an object to HTML attributes? For example I have the following code:

var attrs = new { id = "myid", style = "color: Red;" };

How to convert attrs to string like this to embed them into an HTML markup:

id="myid" style="color: Red;"

Thanks in advance :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...