How to Generate URLs with ASP.NET MVC

I have been working with ASP.NET MVC for some time and yet I still had trouble trying to generate a URL in a view. URL generation is particularly important for ASP.NET MVC because it uses a routing engine to map URLs to code. If we hard code a URL then we lose the ability to later vary our routing scheme.

I have found two ways that currently (ASP.NET MVC preview 2) work to generate URLs in a view. The first uses the GetVirtualPath method and seems overly complicated - so I wrapped it in a global helper:

    public static string GenerateUrl(HttpContext context, RouteValueDictionary routeValues)  
    {  
        return RouteTable.Routes.GetVirtualPath(  
            new RequestContext(new HttpContextWrapper2(context), new RouteData()),  
            routeValues).ToString();  
    }

But then I found that I could achieve the same result more simply using UrlHelper, accessible via the Url property of the view.

// link to a controller
Url.Action("Home");

// link to an action
Url.Action("Home", "Index");

// link to an action and send parameters
Url.Action("Edit", "Product", new RouteValueDictionary(new { id = p.Id }));

Or, if you want the url for a hyperlink you can get that in one step using the ActionLink method on the Html property:

Html.ActionLink(c => c.Index(),"Home")

So I no longer see a need for my GenerateUrl method and have removed it from my helper. All of this would be much easier if there was some documentation. Im sure there is a better way so if you can think of an improvement please leave it in the comments.

This article is part of the GWB Archives. Original Author: Liam McLennan

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.