URL Routing in ASP.Net 4.0

URL Routing

A URL Routing is very important when you are running a community website where user posts articles, forum messages and so on. URL Routing is the process of intercepting an incoming Web request and automatically redirecting it to a different URL. This article discusses the various techniques for implementing URL Routing.

For example

In this example we create a database table with title, description and author name. The title link will be created in the ASP .Net GridView control. when we click on the title link it will be redirected to the dynamic page.

Create a table in the database named Articletable. The table looks like this:

  1. CREATE TABLE [dbo].[Articletable](  
  2.       [ID] [intNOT NULL,  
  3.       [Title] [varchar](200) NULL,  
  4.       [Description] [varchar](400) NULL,  
  5.       [Author] [varchar](50) NULL  
  6. )  

To insert data into the articletable:

  1. INSERT INTO Articletable VALUES(1,'How to validate dropdownlist in asp.net','Here, we will learn how to validate a DropDownList in ASP.NET.','Rohatash Kumar');  
  2. GO  
  3. INSERT INTO Articletable VALUES(2,'Introduction to .NET Assemblies in VB.NET',' Here is a comprehensive introduction to .NET assemblies.','sunil Kumar');  
  4. go  
  5. INSERT INTO Articletable VALUES(3,'BinaryReader and BinaryWriter classes in VB.NET','In this article I will explain about BinaryReader and BinaryWriter Classes in VB.NET.','Deepak Kumar');  
  6. go  
  7. INSERT INTO Articletable VALUES(4,'StreamWriter class in VB.NET','This article shows how to create a new text file and write a string to it.','Rohatash Kumar');  
  8. go  
  9. select * from articletable;
Output

url-Routing-0.jpg

Now in ASP. NET
  1. Open Visual Studio.
  2. Add two webForms to your website, name them URLRouting.aspx and DetailPage.aspx.

Now drag and drop a GridView control from the Toolbox on the URLRouting.aspx page.

Step 1

Define the Route in "Application_Start" of "Global.asax". Also include the namespace "System.Web.Routing".

  1. <%@ Import Namespace="System.Web.Routing" %>  
  2. <%@ Application Language="C#" %>  
  3. <script runat="server">  
  4.     void Application_Start(object sender, EventArgs e)  
  5.     {  
  6.         // Code that runs on application startup  
  7.         RegisterRoutes(RouteTable.Routes);  
  8.     }  
  9.     public static void RegisterRoutes(RouteCollection routeCollection)  
  10.     {  
  11.         routeCollection.MapPageRoute("RouteForArticle""Articles/{id}/{Title}""~/DetailPage.aspx");  
  12.     } 

Now drag and drop a GridView control from the Toolbox on the URLRouting.aspx page. 

Gridview.aspx

The ASP. NET code for the URLRouting page:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="URLReRouting.aspx.cs" Inherits="URL_ReRouting" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <div>  
  10.         <h1>  
  11.             <span style="color: #009900">URL Routing</span></h1>  
  12.         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84"  
  13.             BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"  
  14.             Width="788px" Height="80px">  
  15.             <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />  
  16.             <Columns>  
  17.                 <asp:TemplateField HeaderText="Title">  
  18.                     <ItemTemplate>  
  19.                         <asp:HyperLink ID="HyperLink1" runat="server" CssClass="ArticleTitle" href='<%# GetRouteUrl("RouteForArticle", new {id = Eval("id"), Title= GetTitle(Eval("Title"))})%>'  
  20.                             Text='<%# Eval("Title") %>'>  
  21.                         </asp:HyperLink>  
  22.                     </ItemTemplate>  
  23.                 </asp:TemplateField>  
  24.                 <asp:TemplateField HeaderText="Description">  
  25.                     <ItemTemplate>  
  26.                         <asp:Label ID="lblDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Description")%>'></asp:Label>  
  27.                     </ItemTemplate>  
  28.                 </asp:TemplateField>  
  29.                 <asp:TemplateField HeaderText="Author">  
  30.                     <ItemTemplate>  
  31.                         <asp:Label ID="lblauthor" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Author")%>'></asp:Label>  
  32.                     </ItemTemplate>  
  33.                 </asp:TemplateField>  
  34.             </Columns>  
  35.             <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />  
  36.             <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />  
  37.             <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />  
  38.             <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />  
  39.         </asp:GridView>  
  40.            
  41.     </div>  
  42.     </form>  
  43.     </div> </form>  
  44. </body>  
  45. </html> 
.CS code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data.SqlClient;  
  8. using System.Data;  
  9. public partial class URL_ReRouting : System.Web.UI.Page  
  10. {  
  11.     protected void Page_Load(object sender, EventArgs e)  
  12.     {  
  13.         GridView1.DataSource = GetData();  
  14.         GridView1.DataBind();  
  15.     }  
  16.     private DataTable GetData()  
  17.     {  
  18.         string strConn = ("Data Source=.; uid=sa; pwd=Micr0s0ft; database=TestDB");  
  19.         SqlConnection conn = new SqlConnection(strConn);  
  20.         SqlDataAdapter da = new SqlDataAdapter("select Id,Title,Description,author from Articletable", conn);  
  21.         DataSet ds = new DataSet();  
  22.         da.Fill(ds, "MyTestTable");  
  23.         return ds.Tables["MyTestTable"];  
  24.     }  
  25.     protected string GetTitle(object obj)  
  26.     {  
  27.         return obj.ToString().Replace(' ''-');  
  28.     }  
  29. } 
DetailPage.aspx

The ASP. NET code for the DetailPage.aspx page:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DetailPage.aspx.cs" Inherits="DetailPage" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <div>  
  10.         <h1>  
  11.             Article</h1>  
  12.         <b>Title:</b><asp:Label ID="lblTitle" runat="server" Text="Label" Font-Bold="true"  
  13.             ForeColor="blue"></asp:Label><br />  
  14.         AuthorName<b>:</b><asp:Label ID="lblauthor" runat="server" Text="Label" Font-Bold="true"  
  15.             ForeColor="blue"></asp:Label>  
  16.         <br />  
  17.         <br />  
  18.         <b>Description:</b><br />  
  19.         <asp:Label ID="lblDescription" runat="server" Text="Label"></asp:Label><br />  
  20.         <br />  
  21.         <br />  
  22.         <br />  
  23.     </div>  
  24.     </form>  
  25. </body>  
  26. </html>   
.CS code 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data.SqlClient;  
  8. using System.Data;  
  9. public partial class DetailPage : System.Web.UI.Page  
  10. {  
  11.     protected void Page_Load(object sender, EventArgs e)  
  12.     {  
  13.         if (Page.RouteData.Values["id"].ToString() != null)  
  14.         {  
  15.             string strId = Page.RouteData.Values["id"].ToString();  
  16.             DisplayArticle(strId);  
  17.         }  
  18.     }  
  19.     private void DisplayArticle(string strId)  
  20.     {  
  21.         string strConn = ("Data Source=.; uid=sa; pwd=Micr0s0ft; database=TestDB");  
  22.         SqlConnection conn = new SqlConnection(strConn);  
  23.         SqlDataAdapter da = new SqlDataAdapter("select Id,Title,Description,author from Articletable where Id=" + strId, conn);  
  24.         DataSet ds = new DataSet();  
  25.         da.Fill(ds, "Articletable");  
  26.         lblTitle.Text = ds.Tables["Articletable"].Rows[0][1].ToString();  
  27.         lblDescription.Text = ds.Tables["Articletable"].Rows[0][2].ToString();  
  28.         lblauthor.Text = ds.Tables["Articletable"].Rows[0][3].ToString();  
  29.     }  
  30. } 

 

Now Press F5 to run the application and test it.

url-Routing-1.jpg

Now click on the title link to redirect to the DetailPage.

url-Routing-2.jpg


Similar Articles