ASP.NET 4.0: Bi-Directional Routing using Microsoft Visual Studio 2010


Routing was first introduced with ASP.NET 3.5 SP1 as an alternative to URL rewriting and query strings. Initially routing was limited to the ASP.NET MVC framework only but with release of Microsoft Visual Studio 2010, ASP.NET 4.0 developers can now use routing with web forms also. Using routing, developers can now easily eliminate long URL's and hide file extensions too (like .aspx). Another advantage of URL routing is that developers can now easily hide the physical path/location of web pages residing in the web server.

Routing has new features in ASP.NET 4.0 and the most significant one is URL routing enhancements. Using URL routing developers can now, very easily, decouple the URL with physical files. ASP.NET 4.0 also improves developers' lives by providing the feature "bi-directional URL routing" with the help of components named Route Table, Page Routehandler and ExpressionBuilders. In this article I will show you an example of bi-directional URL routing using Visual Studio 2010.

Bi Directional Routing Application Demo

Using the bi-directional routing feature, developers can now generate URL's on the fly. No need to hard code URLs in several places of your application. To demonstrate bi-directional URL routing, I have created an ASP.NET application and added an employee master database (added a SQL Server database to ASP.NET solution).

Figure 1

In this database I have created an employee details table with the following columns:

EmployeeName  Data type - nvarchar(100)	
EmployeeSalary  Data type - numeric(18, 2)	
EmployeeId	     Data type - int	
Department	     Data type - nvarchar(100)	
Age	               Data type - int	
Skillset	     Data type - nvarchar(1000)	
Role	               Data type - nvarchar(50)

Next, to test my bi directional URL routing application, I have also added sample data to my employee details table.

Figure 2

Now, to implement web form routes I have added Global.asax to my Microsoft Visual Studio solution and written the following code snipped in the Application_Start event. This will create a route for my employee department and I will be able to see department wise employee details by typing a short URL in my browser. Like this, http://localhost:1488/Department/IT, instead of http://localhost:1488/EmployeeDetails.aspx?Department=IT .

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 BiDirectionalRouting
    public class Global : System.Web.HttpApplication

        void Application_Start(object sender, EventArgs e)
           // Adding Routing Information ASP.NET 4.0   
            RouteTable.Routes.MapPageRoute("Department", "Department/{Name}", "~/EmployeeDetails.aspx");


The MapPageRoute function that you can see in the above code snippet is introduced in ASP.NET 4.0. This method has 3 overloaded versions as follows.

  1. MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess)
  2. MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess, RouteValueDictionary defaults)
  3. MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess, RouteValueDictionary defaults, RouteValueDictionary constraints)

The same employee department route can be achieved in ASP.NET 3.5 by writing the following code snippet in the Application_Start event.

   // Adding Routing Information ASP.NET 3.5
   RouteTable.Routes.Add ("Department", new Route("Department/{Name}",new    

Next, to handle all incoming web form URL requests, I have used ExpressionBuilders introduced in ASP.NET 4.0. I have used ASP:HyperLink web controls to generate hyperlinks at runtime. The following code snippet shows how these hyperlinks are created.

    <asp:Label ID="Label1" runat="server"  text="Select Department : " ></asp:Label>    
         <asp:HyperLink ID="HyperLinkIT" runat="server" 
           NavigateUrl="<%$RouteUrl:RouteName=Department, Name=IT%>"  Text="Dept IT" />
         <asp:HyperLink ID="HyperLinkSales" runat="server" 
           NavigateUrl="<%$RouteUrl:RouteName=Department, Name=Sales%>"  Text="Dept Sales" />
         <asp:HyperLink ID="HyperLinkMarketting" runat="server" 
           NavigateUrl="<%$RouteUrl:RouteName=Department, Name=Marketting%>"  Text="Dept Marketting" />
           <asp:HyperLink ID="HyperLinkHR" runat="server" 
           NavigateUrl="<%$RouteUrl:RouteName=Department, Name=HR%>"  Text="Dept HR" />

Using RouteUrl (an expression builder) I have created hyperlink URL's dynamically based on the parameter received in the request. In ASP.NET 3.5 we had to hardcode the URL's again and again but using RouteUrl this hard coding has been eliminated. Expression builders are provided with ASP.NET 4.0 to achieve bi-directional routing. There are 2 types of expression builder named RoutURLExpressionBuilder and RoutValueExpressionBuilder.

ASP.NET 4.0: Bi-Directional Routing using Microsoft Visual Studio 2010

Next, I have created a SQL data source and a command object to fetch employee details from the employee master database based on the route value parameter (department name as filter criteria in the SQL statement).

  <asp:sqldatasource id="SqlDataSourceEmployee" runat="server" connectionstring="<%$    
    ConnectionStrings:EmployeeConnection %>"
      selectcommand="SELECT EmployeeName, EmployeeSalary, Age, SkillSet,Role FROM TblEmployee where 
        Department = @Department">
          <asp:routeparameter name="Department" RouteKey="Name"  />

The connection string mentioned in the above code snippet is already defined in the web.config file.

<add name="EmployeeConnection"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\EmployeeDatabase.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />

Next, I have created a datalist object to display all employee information retrieved from the employee master database, based on the department filter criteria. I have also added AJAX ScriptManager and UpdatePanel for partial post back of the web form.

     <asp:ScriptManager ID="ScriptManager1" runat="server">
      <asp:UpdatePanel ID="UpdatePanel1" runat="server">
     <asp:DataList ID="DataListEmployee" runat="server" DataSourceID="SqlDataSourceEmployee">
      <ItemTemplate >
        Employee Name:
        <asp:Label ID="EmployeeNameLabel" runat="server" Text='<%# Eval("EmployeeName") %>' />
        <br />
        Employee Salary:
        <asp:Label ID="EmployeeSalaryLabel" runat="server" Text='<%# Eval("EmployeeSalary") %>' />        
        <br />
        Employee Age:
        <asp:Label ID="EmployeeAgeLabel" runat="server" Text='<%# Eval("Age") %>' />        <br />
           Employee SkillSet:
        <asp:Label ID="EmployeeSkillLabel" runat="server" Text='<%# Eval("SkillSet") %>' />        <br />
        Employee Role:
        <asp:Label ID="EmployeeRoleLabel" runat="server" Text='<%# Eval("Role") %>' />        <br />

To see the output of my bi-directional routing sample application I pressed F5 in The Microsoft Visual Studio Editor. This opens a new browser window. Once I click on any department (Like Dept IT, Dept Sales etc) shows all employee lists present in the database for selected department. Now if you see the URL in the browser it will look like http://localhost:1488/Department/{Department Name}.

[solution-3.jpg] Figure 3


With help of bi-directional routing we can now create customized URL's. This helps developers to hide the physical path of a web page. From an application security point of view this feature is a great addition to ASP.NET 4.0. Moreover routing helps us to configure our web applications to accept any requested URL which might not have any physical mapping files.

Related Articles



  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Today's "average" business in general is ever more reliant on technology and the Internet. Mobility is the most often cited business trend that has transformed the way many of us work and communicate. From an IT security perspective, this means that protection methods and tools from even a few years ago are rapidly becoming "unfit for purpose." This guide provides crucial facts to assist you in building a robust business case, meeting the demands of your business, and protecting against threats now and in the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds