How to support htmlAttributes parameters in HtmlHelper extensions?

I am creating HtmlHelper extension methods. Many of the built-in structure methods support parameters such as htmlAttributes (object types) that are rendered in the resulting HTML. How can I provide overloads of my own methods that also support the htmlAttributes parameter without overwriting the string concatenation logic to display them as attributes in a tag?

+7
source share
1 answer

The HtmlHelper object has a method that converts the object into a dictionary of names / values, which you can then combine into your tag as it is created. For example, this code will generate a <script> with any additional attributes:

 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 the default values ​​to provide a null value for htmlAttributes , which will lead to the creation of an empty Dictionary .

(This method also degrades attribute names in valid HTML attributes, etc., so it is safe to use for almost any object.)

+17
source

All Articles