views:

49

answers:

3

If a html helper takes a idictionary as a parameter, how do I use it?

I tried:

<%= Html.Blah( new { id = "blah" }) %>

But that doesn't work.

+9  A: 
<%= Html.Blah( new Dictionary<string, object>(){
                                                   { "key", "value" },
                                                   { "key1", someObj },
                                                   { "blah", 1 }
                                               } );
Justin Niessner
A: 

If you don't want to use Generic Dictionary, Hashtable implements IDictionary as well.

 Html.Blah(new Hashtable(){
                        {"id", "blah"}
                    });
cellik
A: 

The built-in HtmlHelper extension methods typically provide overloads that take an object parameter instead of IDictionary<string, object> in order to allow you to call them using an anonymous type as you tried.

If this is your own method, you could create another extension method that looks something like this:

    public static string Blah(this HtmlHelper html, object htmlAttributes)
    {
        return html.Blah(new RouteValueDictionary(htmlAttributes));
    }

The RouteValueDictionary's constructor takes an object and populates itself using the public properties of the object passed in. I believe this is typically what the built-in HtmlHelper extension methods do as well.

Alternatively, you could call the method like this:

        html.Blah(new RouteValueDictionary(new { id = "blah" }));

I haven't looked, but it seems obvious that the RouteValueDictionary class is doing some reflection in order to be able to identify the properties of the object. Just be aware, in case that is something you are concerned about.

Dr. Wily's Apprentice