views:

33

answers:

1

Hi all

I have a Html helper method with the following signature:

public static string MyActionLink(this HtmlHelper html
, string linkText
, List<KeyValuePair<string, object>> attributePairs
, bool adminLink){}

I have another utility then that takes all the attribute pairs and merges them to the tag as attribute/value pairs:

ExtensionsUtilities.MergeAttributesToTag(tag, attributePairs);

and everything is fine. The problem, however, is that the parameter

, List<KeyValuePair<string, object>> attributePairs

is a bit cumbersome in the definition, and even moreso in the use of the Helper method:

<span class="MySpan">  
    <%= Html.MyActionLink(Html.Encode(item.Name)
        , new List<KeyValuePair<string, object>>
               {
                   Html.GetAttributePair("href", Url.Action("ACTION","CONTROLLER")),
                   Html.GetAttributePair("Id", Html.Encode(item.Id)),
                   Html.GetAttributePair("customAttribute1", Html.Encode(item.Val1)),
                   Html.GetAttributePair("customAttribute2", Html.Encode(item.Val2))
               }, false)%>
</span>

(Html.GetAttributePair() just returns a KeyValuePair in an attempt to tidy things a bit)

I'm just curious now if somebody could suggest a different (maybe more efficient & developer-friendly) approach to acheiving the same result?

Thanks Guys

Dave

+1  A: 

How about using an anonymous type:

public static string MyActionLink(
    this HtmlHelper html, 
    string linkText, 
    object attributePairs, 
    bool adminLink)
{}

Which could be called like this:

<%= Html.MyActionLink(
    Html.Encode(item.Name), 
    new { 
        href = Url.Action("ACTION","CONTROLLER"),
        id = tml.Encode(item.Id),
        customAttribute1 = Html.Encode(item.Val1),
        customAttribute2 = Html.Encode(item.Val2)
    },
    false) %>

UPDATE:

And here's how to convert the anonymous type into a strongly typed dictionary:

var values = new 
{ 
    href = "abc",
    id = "123"
};

var dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
if (values != null)
{
    foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
    {
        object value = descriptor.GetValue(values);
        dic.Add(descriptor.Name, value);
    }
}
Darin Dimitrov
Hi Darin, thanks for the reply. This is a good clear answer and it _almost_ works... except I can't now convert the type back into an object that I can iterate over for my ExtensionsUtilities.MergeAttributesToTag(tag, attributePairs);line. I can see though that the anonymous type could be useful for me in other parts of my app so I'm still very happy to see your reply :-)
DaveDev
@Darin, thanks. This is great.
DaveDev