ASP.Net MVC: Create a link method… ie JUST GIVE ME THE STUPID URL

One thing that kind of annoys me is the situation where you just want a url, but you don’t want one of the prepackaged links using:


Mostly because you want to be able to create your own html and you only want the created url. Well turns out there’s a method for this: The RouteUrl method on the UrlHelper class. Down side is that it’s not static and takes a few lines to use, so not cool UI design side. Well here’s a method that uses that method and gives you a method to exact a method of victory. I think that sentence had promise, but fell short of complete failure.

Anyways, here it is… The “Just give me the stupid url” method, CreateUrl for short.

        public static String CreateUrl
          RequestContext context,
          RouteCollection routeCollection,
          String routeName,
          String controller,
          String action,
          RouteValueDictionary routeValues
            //Create the helper
            UrlHelper neededHelper = new UrlHelper(context, routeCollection);

            //get the route to check what it is holding at far
            //as defaults go
            var neededRoute = (Route)routeCollection[routeName];

            //this might be overkill honestly.  Basically in case the
            //Route contains the "controller" key only then add it to the
            //values for the route.  Otherwise just ignore.  It's possible
            //someone might pass in a controller/action but the route
            //doesn't take them. At which point you'll
            //be showing the "Aw maaaaan" face.

            if (!String.IsNullOrEmpty(controller) && neededRoute.Defaults.ContainsKey("controller"))
                routeValues.Add("controller", controller);

            if (!String.IsNullOrEmpty(action) && neededRoute.Defaults.ContainsKey("action"))
                routeValues.Add("action", action);

            //And then the call to create the url string.
            return neededHelper.RouteUrl(routeName, routeValues);

And in use View side:

  <a href="
    new RouteValueDictionary { { "id", 1 } }
  Something is linked

Now mind you I did use a link there so it seems like a silly example. However, you can do many other things now that you just have the url itself.