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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With