Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Support htmlAttributes Parameters in HtmlHelper Extensions?

Tags:

asp.net-mvc

I'm creating HtmlHelper extension methods. Many of the built-in framework methods support parameters like htmlAttributes (of type object) that get rendered onto the resultant HTML. How can I provide overloads of my own methods that also support an htmlAttributes parameter without rewriting the string concatenation logic to render them as attributes on the tag?

like image 985
blaster Avatar asked Mar 12 '12 14:03

blaster


1 Answers

The HtmlHelper object has a method that converts an object into a name/value dictionary, which you can then merge into your tag as it's being built. For example, this code will generate a <script> tag with whatever extra attributes are passed in:

var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) as IDictionary<string, object>;

TagBuilder tag = new TagBuilder("script");
tag.MergeAttributes(attributes);
tag.MergeAttribute("type", "text/javascript");
tag.MergeAttribute("src", scriptPath);

You can either provide overloads or use default values to supply a null value for htmlAttributes, which will produce an empty Dictionary.

(The method also sanitizes the attribute names into valid HTML attributes, etc. so it's safe to use on just about any object.)

like image 141
Michael Edenfield Avatar answered Nov 19 '22 11:11

Michael Edenfield