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

Introduction

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 .

<code>
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");
   
        }
    }
 }

</code>

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.

<code>
   // Adding Routing Information ASP.NET 3.5
   RouteTable.Routes.Add ("Department", new Route("Department/{Name}",new    
   PageRouteHandler("~/EmployeeDetails.aspx")));
   
</code>

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.

<code>
  <div>
    <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" />
   </div>
</code>

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).

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

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

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

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.

<Code>
    <div>
     <asp:ScriptManager ID="ScriptManager1" runat="server">
     </asp:ScriptManager>
      <asp:UpdatePanel ID="UpdatePanel1" runat="server">
      <ContentTemplate>
      <fieldset>
     <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 />
    </ItemTemplate>
  </asp:DataList>
  </fieldset>
  </ContentTemplate>
   </asp:UpdatePanel>
     </div> 
</Code>

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

Conclusion

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





Downloads

Comments

  • 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: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds