开发者

Passing Collection to MVC.NET HtmlHelpers More Efficiently? Suggestions?

I have a Html helper method with the following signa开发者_高级运维ture:

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


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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜