2

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

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I should. I have no idea how I missed that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.