This topic has not yet been rated - Rate this topic

How to: Construct URLs from Routes

ASP.NET routing enables you to programmatically generate URLs that are based on route definitions. You specify parameter values and if it is required a route name, and ASP.NET generates a URL string that corresponds to a matching route. If you change route URL patterns, you do not have to change the code or markup that generates URLs unless the parameters in the patterns are changed.

For more information about routing, see ASP.NET Routing.

When ASP.NET routing constructs a URL, it uses the first route that has a pattern that matches the parameters that you provide, unless you specify a route name. If you specify a route name, ASP.NET uses the named route.

The following procedures describe how to create a URL by using code and by using markup.

To create a URL by using code

  1. Create an instance of the RouteValueDictionary class that contains all the parameter values that you want to include in the URL. The parameters must match a route URL pattern.

    The RouteValueDictionary object can include parameters in addition to the ones that match a route URL pattern. If it does, those values are assigned to the query string.

  2. Call the GetVirtualPath method of the RouteCollection class and pass the RouteValueDictionary object in order to construct the URL. To indicate a specific route, include the route name.

    The GetVirtualPath method returns a VirtualPathData object.

  3. From the VirtualPathData object, retrieve the VirtualPath property to get the string that represents the URL.

To create a URL by using markup

  • Create a RouteUrl expression that contains the parameter names and values that you want to include in the URL.

    The parameter values must include values that match a route pattern. If you include extra values, those values are assigned to the query string.

    The following example shows a RouteUrl expression that specifies one parameter.

    <asp:HyperLink ID="HyperLink1" runat="server"
      NavigateUrl="<%$RouteUrl:year=2007%>">
      Data for 2007</asp:HyperLink>
    

    The following example shows a RouteUrl expression that specifies multiple parameters.

    <asp:HyperLink ID="HyperLink1" runat="server"
      NavigateUrl="<%$RouteUrl:year=2007, locale=CA%>">
      Data for California (2007)</asp:HyperLink>
    

    The following example shows a RouteUrl expression that specifies multiple parameters and a route name.

    <asp:HyperLink ID="HyperLink1" runat="server"
      NavigateUrl="<%$RouteUrl:year=2007, locale=CA,PathName=%>">
      Data for California (2007)</asp:HyperLink>
    
    NoteNote

    The RouteUrl expression can be used only in the markup for a server control.

The following example shows how to create a URL from a route by using code. The example assumes that you have added two routes to the ASP.NET application. The first route is named SalesRoute and defines the pattern SalesReport/{locale}/{year}. The second route is named ExpensesRoute and defines the pattern ExpensesReport/{locale}/{year}/{querystring}. For more information, see How to: Define Routes for Web Forms Applications.

The example shows how to specify the name of the route when you construct the URL. Both SalesRoute and ExpensesRoute take the parameters year and locale. Therefore, you specify the route that you want by using a name. It is not necessary to specify a name if the list of parameters is sufficient to identify the intended route.

The example also shows how to include an extra parameter when you construct the URL. The category parameter will be included as a query-string value when the URL is constructed because there no placeholder named category in the URL pattern for the route.


RouteValueDictionary parameters = 
    new RouteValueDictionary  
        { 
            {"locale", "CA" }, 
            { "year", "2008" } , 
            { "category", "recreation" }
        };

VirtualPathData vpd = 
    RouteTable.Routes.GetVirtualPath(null, "ExpensesRoute", parameters);

HyperLink6.NavigateUrl = vpd.VirtualPath;


Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
VB example missing category
If you're reading in VB mode be aware that the comment above the example mentions an extra "category" parameter, but this is missing from the VB example (so take a peek at the C# example).
The magic nobody mentions

What nobody ever seems to mention is how GetVirtualPath uses the supplied route parameter values to match a route in the route table.

First, the route table is searched top to bottom until some route's GetVirtualPath returns a value. 

Second ... all the default parameters defined in the route are taken as mandatory by GetVirtualPath

So if we have a route like

routes.MapRoute( "Route", "{p1}/{p2}/{p3}" /* the pattern */,
                new { p2 = "x", p3 = "z", p4 = "y" } /* defaults */ );

and

routes.GetVirtualPath( null, new { p1 = "a", p2 = "b", p4 = "y" } ); /* values */

We can say that the pattern's p2 "eats" the default's p2 (and also any p2 provided value).

The same for p3 .. in this case values does not have a p3 so it is dropped from the resulting url.

Parameter p1 is mandatory (in values) because there is no default, which could be empty) {I think} 

Now, tricky ... p4 is required in values because there is no parameter p4 in the pattern.

And this is why all the routes like

routes.MapRoute( "xxx", "Item/{id}", new { controller="Blog", action="List" } );

will be chosen by GetVirtualPath to generate the URl for ActionResult = Blog.List(13);
(route values = new { controller="Blog", action = "List", id = 13 }).