2

I am trying to use replicate the syntax for most of the standard HtmlHelpers where an object is used to add Html attributes to a generated tag.

I would like to have something like:

<%: Html.MyCustomHelper("SomeValue", new { id="myID", @class="myClass" })%>

How do I access the keys of that new object so I can add attributes from the view?

Would this use reflection? I've heard that word thrown around a bit, but I'm not familiar with it.

2 Answers 2

4

The built-in helper methods use RouteValueDictionary to convert the object into a dictionary. They also provide two overloads for accepting HTML attributes, one which accepts an object, and one which accepts an IDictionary<string, object>:

public static string MyCustomHelper(this HtmlHelper htmlHelper, string someValue, object htmlAttributes)
{
    return htmlHelper.MyCustomHelper(someValue, new RouteValueDictionary(htmlAttributes));
}

public static string MyCustomHelper(this HtmlHelper htmlHelper, string someValue, IDictionary<string, object> htmlAttributes)
{
    // Get attributes with htmlAttributes["name"]
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

This ability was created by Eilon Lipton on the MVC Team. Details are here - and download the provided code to roll your own.

http://weblogs.asp.net/leftslipper/archive/2007/09/24/using-c-3-0-anonymous-types-as-dictionaries.aspx

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.