7

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?

1
  • What do you have so far? Commented Mar 12, 2012 at 14:51

1 Answer 1

17

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.