2014-10-27 48 views
2

我想创建一些HTML帮助器函数来创建一些带有生成HTML内容的链接。我会尽可能遵循默认的API。当我想传递一个routevalues对象时,这会变得棘手。一个类型为RouteValueDictionary的routevalue对象是(有意?)在MVC中创建麻烦。我想通过object routevalues,就像Html.ActionLink那样。棘手的部分是,我似乎需要UrlHelper.CreateUrl需要RouteValueDictionary。我查看了ActionLink如何在内部执行此操作,并使用TypeHelper.ObjectToDictionary。然而,这是一个内部类,所以我不能访问它。我可以复制粘贴这些东西,但除此之外,首先我会违反许可证,如果我这样做,并且没有根据Apache 2.0许可证或兼容许可证进行许可,其次,复制粘贴编程会给我heeby- jeebies。用html内容创建链接

下面是我想大概喜欢做的事:

public static MvcHtmlString MyFancyActionLink(this HtmlHelper helper, 
               Foo foo, 
               object routevalues){ 
    TagBuilder inner = fancyFooContent(foo); 
    RouteValueDictionary routedict = TypeHelper.ObjectToDictionary(routevalues); 
    //alas! TypeHelper is internal! 
    string url = UrlHelper.GenerateUrl(null, 
            "myaction", 
            "mycontroller", 
            routedict, 
            helper.ViewContext.RequestContext, 
            true); 
    TagBuilder link = new TagBuilder("a"); 
    link.MergeAttribute("href", url); 
    link.InnerHtml = inner.toString(); 
    return MvcHtmlString.Create(link.ToString()); 
} 
+1

你能更新你的版本吗? https://aspnetwebstack.codeplex.com/workitem/1737 – RobH 2014-10-27 11:47:50

回答

4

RouteValueDictionary有constructor接受的对象,并将其属性来填充字典。除非我在这里丢失了一些明显的东西,你应该可以使用:

RouteValueDictionary routedict = new RouteValueDictionary(routevalues); 
+0

我应该。我不知道我是如何错过的。 – Martijn 2014-10-27 13:10:20