Martijn
Martijn

Reputation: 12102

Creating link with html content

I would like to create some HTML helper functions to create some links with generated HTML content. I would follow the default API as much as possible. This gets tricky when I want to pass in a routevalues object. A routevalue object of type RouteValueDictionary is (intentionally?) cumbersome to create in MVC. I would like to pass in an object routevalues as is done with i.e. Html.ActionLink. The tricky part is that I seem to need UrlHelper.CreateUrl which requires a RouteValueDictionary. I checked how ActionLink does this internally, and it uses TypeHelper.ObjectToDictionary. TypeHelper however is an internal class, so I can't access that. I could copy-paste the thing in, but - apart from that firstly i'd be violating the license if I do that and don't license under the Apache 2.0 license or compatible, and secondly copy-paste programming gives me the heeby-jeebies.

The following is what I'd roughly like to do:

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

Upvotes: 2

Views: 293

Answers (1)

Andrei
Andrei

Reputation: 56688

RouteValueDictionary has a constructor that accepts an object and uses its properties to populate the dictionary. Unless I am missing something obvious here, you should be able to use that:

RouteValueDictionary routedict = new RouteValueDictionary(routevalues);

Upvotes: 4

Related Questions