URL Routing in ASP.Net 4 Web Forms

ASP.Net 4 simplifies the routing experience introduced in ASP.NET 3.5 SP1. Routing allows the use of more meaningful or 'friendly' URLs (which may also benefit search engine ranking).

For example, rather than .../ShowCountryDetails.aspx?country=australia routing could be enabled so the url looked like .../countries/australia

Defining Routes

You can define routes using the MapPageRoute method of the RouteCollection class. The code below is an extract from Global.asax.cs, the method RegisterRoutes is called from application start, and it's here that a route is registered:

protected void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(RouteTable.Routes);
}



void RegisterRoutes(RouteCollection routes)
{
    /*  Create a routing which maps SayHello to ShowGreeting.aspx
        and defines 2 parameters, greeting and name. */
    routes.MapPageRoute("ShowGreetingRoute",
        "SayHello/{greeting}/{name}",
        "~/ShowGreeting.aspx");
}
 

Accessing URL Param Values In Markup

When routing is in use, RouteValue expressions can be used in markup:

<asp:Literal Text="<%$RouteValue:greeting%>" runat="server" />

Accessing URL Param Values In Code

In code we can use Page.RouteData to get the values of any routed URL parameter values; we can either check for a null before calling ToString() or as in the following example use ContainsKey to check first (in practice you wouldn't use 'magic' string literals for "greeting", rather you'd define these as constants, etc.):

string greetingText = "no greeting text specified";
       
if (Page.RouteData.Values.ContainsKey("greeting"))
        greetingText = Page.RouteData.Values["greeting"].ToString();

Creating Routed URLs in Markup

We can create routed URLs in markup by using RouteUrl expressions:

<asp:HyperLink ID="declarativeLinkToRoutedPage"
    NavigateUrl="<%$RouteUrl:greeting=bonjour, name=Bob, routename=ShowGreetingRoute%>"
    Text="Say hello to Bob in French" runat="server" />

Creating Routed URLs in Code

Instead of setting NavigateUrl using RouteUrl in markup, we could set it in code RouteValueDictionary & VirtualPathData:

/// <summary>
/// Example of setting a Hyperlink's NavigateUrl in code
/// </summary>
private void SetHyperlinkNavigateUrlProperty()
{
    RouteValueDictionary routeParamValues = new RouteValueDictionary
    {
        {"greeting", "goodnight"},
        {"name", "Fred"}
    };

    VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, routeParamValues);

    linkSetInCodeToRoutedPage.NavigateUrl = vpd.VirtualPath;
}

Using Routed Values as Parameters in Bound Data Sources

We can define RouteParameter in a data source that is being bound to.

The following markup shows a DetailsView being bound to an ObjectDataSource. The SelectParameters collection defines a RouteParameter which will pass the value of the 'name' URL routed parameter to the GetPersonsAge method of the MockDataBase class.

<asp:ObjectDataSource ID="odsPersonsAge" runat="server"
    SelectMethod="GetPersonsAge" TypeName="ASPNET4Routing.MockDataBase">
    <SelectParameters>
        <asp:RouteParameter Name="name" RouteKey="name" Type="String" />
    </SelectParameters>
</asp:ObjectDataSource>
      
<asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="odsPersonsAge"
                AutoGenerateRows="true" /> 

<asp:ObjectDataSource ID="odsPersonsAge" runat="server"
    SelectMethod="GetPersonsAge" TypeName="ASPNET4Routing.MockDataBase">
    <SelectParameters>
        <asp:RouteParameter Name="name" RouteKey="name" Type="String" />
    </SelectParameters>
</asp:ObjectDataSource>

SHARE:

Add comment

Loading