tags:

views:

1150

answers:

1

Hi

In asp.net mvc I always see the built in html helpers they always have object htmlAttirbutes.

Then I usually do new {@id = "test", @class="myClass"}.

How do I extract a parameter like this in my own html helpers?

Like I am using "HtmlTextWriterTag" is their a way I can pass this whole object to the writer and it figured it out or what?

Also how does this work with big html helpers?

Like I am making a html helper and it uses all these tags.

Table
thead
tfooter
tbody
tr
td
a
img

Does that mean I have to make a html Attribute for each of these tags?

+11  A: 

I usually do something like this:

   public static string Label(this HtmlHelper htmlHelper, string forName, string labelText, object htmlAttributes)
    {
        return Label(htmlHelper, forName, labelText, new RouteValueDictionary(htmlAttributes));
    }

    public static string Label(this HtmlHelper htmlHelper, string forName, string labelText,
                               IDictionary<string, object> htmlAttributes)
    {
        // Get the id
        if (htmlAttributes.ContainsKey("Id"))
        {
            string id = htmlAttributes["Id"] as string;
        }

        TagBuilder tagBuilder = new TagBuilder("label");
        tagBuilder.MergeAttributes(htmlAttributes);
        tagBuilder.MergeAttribute("for", forName, true);
        tagBuilder.SetInnerText(labelText);
        return tagBuilder.ToString();
    }

I suggest you to download the ASP.NET MVC source from the codeplex and take a look at the built in html helpers.

rrejc
turns out your example is more informative than the source. i couldn't figure out how the source worked as it was expected an IDictionary (like your label does) but i was trying to pass it the anonymous object. Once I saw you convert it to a RouteValueDictionary is made more sense.
Sailing Judo