URL Routing with ASP.NET 4.0
page 2 of 3
by Rohit Sinha
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 32168/ 64

ASP.NET 4.0 & URL Routing

Initially URL Routing was introduced with ASP.NET MVC. It was a great start but cleaner version was launched with ASP.NET 3.5 SP1 where System.Web.Routing assembly (originally part of ASP.NET MVC) introduced. However here you were needed to create your own IRouteHandler and implement GetHTTPHandler method.

ASP.NET 4.0 is definitely going to take us much ahead with built-in support for URL routing. Here you got all necessary components to enable routing in much easier way. Now no need of implementing IRouteHandler, ASP.NET 4.0 already provided a readymade PageRouteHandler class which picks the appropriate PageHandler to service the request and provides properties and methods for defining URL mapping to a physical file. It has got ExpressionBuilders for bi-directional support.

Let’s drill down further with an example. We will prepare a web application where a user can see Contact details (name and age) based on selected State i.e. the URL will have a URL pattern like - /State/{State Came}. This will list all the contacts for specified state name. For CA the URL should be - http://localhost:4951/State/CA , where State is the key and CA is the value. User can further go ahead and directly change the URL (CA to NY) and see desired results.

Let’s proceed step by step:

·         I have shown below a snapshot of the database table which this application will be using for Contacts:

·         Open VS 2010 solution and select ASP.NET Web Application

·         Add Global.asax to current web application:

·         Create a new route by adding route to a RouteTable. RouteTable stores different routes (URL patterns) which are used for processing the requests to construct URLs dynamically. We want to add routes to RouteTable on start of the application.  We need to pass the instance of PageRouteHandler to the Route constructor and map URL to physical file. PageRouteHandler is the class under System.Web.Routing which defines how URL maps to a physical file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;
namespace URLRouting
    public class Global : System.Web.HttpApplication
        protected void Application_Start(object sender, EventArgs e)
            RouteTable.Routes.Add("State"new Route("State/{Name}", 
              new PageRouteHandler("~/Default.aspx")));

·         Now we have defined that any URL with pattern like “State/{Name}” will be handled by Default.aspx where {Name} is a placeholder for state name. We will use Default.aspx and handle the incoming request with ExpressionBuilders:

·         Above picture shows how bi-directional routing is implemented. Hyperlinks are generated on the fly. Let’s explore this in more detail.

·         RouteUrl is an expression builder which builds the correct URL on the dynamically based on supplied parameters. So you do not to hardcode the URL e.g.

<asp:HyperLink ID="HyperLink1" runat="server" 
    NavigateUrl="<%$RouteUrl:RouteName=State, Name=TX%>"  Text="Texas" />

This will actually evaluate to following URL based on defined route under RouteTable:

<asp:HyperLink ID="HyperLink1" runat="server" 
    NavigateUrl=http://localhost:4951/State/TX  Text="Texas" />

·         We need Hyperlinks for different states (TX, CA and NY) and URL to be evaluated with ExpressionBuilders:

<asp:Label ID="Label2" runat="server"  text="Select State : " ></asp:Label>    
         <asp:HyperLink ID="HyperLinkTX" runat="server" 
           NavigateUrl="<%$RouteUrl:RouteName=State, Name=TX%>"  Text="Texas" />
         <asp:HyperLink ID="HyperLinkCA" runat="server" 
           NavigateUrl="<%$RouteUrl:RouteName=State, Name=CA%>"  Text="California" />
         <asp:HyperLink ID="HyperLinkNY" runat="server" 
           NavigateUrl="<%$RouteUrl:RouteName=State, Name=NY%>"  Text="NewYork" />

·         We need to show the selected State as “List of Contacts from: <state code>. State Code (TX, CA or NY) are stored as value of the route parameter. There are different ways to get the value.  You can use the Route object

1.    RouteData.Values["name"];

2.    Use an expression builder:

<%$ RouteValue:name %>

·         We will use expression builder <%$ RouteValue:name %>

        <asp:Label ID="Label1" runat="server"  Font-Bold=true 
          text="List of Contacts from : " ></asp:Label>    
        <asp:Label ID="lblRouteData" runat="server" Font-Bold=true 
          text="<%$RouteValue:Name%>" ></asp:Label>

·         Now create a sqldatasource, assign connection string and use RouteParameter to pass parameters. RouteParameter basically binds the value of URL to a parameter object. Its Routekey property will be used to retrieve the value of a placeholder. You can also put DefaultValue if you need.

<asp:sqldatasource id="SqlDataSource1" runat="server"  
   connectionstring="<%$ ConnectionStrings:MyConnection %>"
   selectcommand="SELECT Name, Age FROM ContactInfo where State=@StateCode">
       <asp:routeparameter name="StateCode" RouteKey="Name"  />

·         As shown above, we will query a table ContactInfo with StateCode is passed to retrieve the details of a specific state.

·         We will show the results in following DataList control:

<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1">
        <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
        <br />
        <asp:Label ID="AgeLabel" runat="server" Text='<%# Eval("Age") %>' />        <br /><br />

·         Off course there will be a Connection String (“MyConnection”) in Web.Config:

<add name="MyConnection" connectionString="Data Source=LENOVO-F4A0E849\MSSMLBIZ;
Initial Catalog=Test;Integrated Security=True" />

·         Finally this is how output web page will be shown:

·         User selects Texas by clicking the hyperlink. It will redirect to /State/TX, this pattern in turn mapped to Default.aspx (earlier defined in the RouteTable).

·         See below the status bar showing generated URL when you move your mouse over to Texas. This is generated through ExpressionBuilder.

·         Now user selects NY, this is how it shows the details of contacts under selected state.

View Entire Article

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-11-21 6:19:09 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search