URL Routing in ASP.Net 4.0

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.

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:

CREATE TABLE [dbo].[Articletable](

      [ID] [int] NOT NULL,

      [Title] [varchar](200) NULL,

      [Description] [varchar](400) NULL,

      [Author] [varchar](50) NULL

)

To insert data into the articletable:

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');

GO

INSERT INTO Articletable VALUES(2,'Introduction to .NET Assemblies in VB.NET',' Here is a comprehensive introduction to .NET assemblies.','sunil Kumar');

go

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');

 

go

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');

go

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

<%@ Import Namespace="System.Web.Routing" %>

<%@ Application Language="C#" %>

 

<script runat="server">

 

    void Application_Start(object sender, EventArgs e)

    {

        // Code that runs on application startup

        RegisterRoutes(RouteTable.Routes);

    }

    public static void RegisterRoutes(RouteCollection routeCollection)

    {

        routeCollection.MapPageRoute("RouteForArticle", "Articles/{id}/{Title}", "~/DetailPage.aspx");

    }   

 

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:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="URLReRouting.aspx.cs" Inherits="URL_ReRouting" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <h1>

            <span style="color: #009900">URL Routing</span></h1>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84"

            BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"

            Width="788px" Height="80px">

            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />

            <Columns>

                <asp:TemplateField HeaderText="Title">

                    <ItemTemplate>

                        <asp:HyperLink ID="HyperLink1" runat="server" CssClass="ArticleTitle" href='<%# GetRouteUrl("RouteForArticle", new {id = Eval("id"), Title= GetTitle(Eval("Title"))})%>'

                            Text='<%# Eval("Title") %>'>

                        </asp:HyperLink>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Description">

                    <ItemTemplate>

                        <asp:Label ID="lblDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Description")%>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Author">

                    <ItemTemplate>

                        <asp:Label ID="lblauthor" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Author")%>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />

            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />

            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />

            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />

        </asp:GridView>

        &nbsp;

    </div>

    </form>

    </div> </form>

</body>

</html>

.CS code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Data;

 

public partial class URL_ReRouting : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        GridView1.DataSource = GetData();

        GridView1.DataBind();

    }

 

    private DataTable GetData()

    {

        string strConn = ("Data Source=.; uid=sa; pwd=Micr0s0ft; database=TestDB");

        SqlConnection conn = new SqlConnection(strConn);

        SqlDataAdapter da = new SqlDataAdapter("select Id,Title,Description,author from Articletable", conn);

        DataSet ds = new DataSet();

        da.Fill(ds, "MyTestTable");

        return ds.Tables["MyTestTable"];

    }

 

    protected string GetTitle(object obj)

    {

        return obj.ToString().Replace(' ', '-');

    }

}

DetailPage.aspx

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

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DetailPage.aspx.cs" Inherits="DetailPage" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <h1>

            Article</h1>

        <b>Title:</b><asp:Label ID="lblTitle" runat="server" Text="Label" Font-Bold="true"

            ForeColor="blue"></asp:Label><br />

        AuthorName<b>:</b><asp:Label ID="lblauthor" runat="server" Text="Label" Font-Bold="true"

            ForeColor="blue"></asp:Label>

        <br />

        <br />

        <b>Description:</b><br />

        <asp:Label ID="lblDescription" runat="server" Text="Label"></asp:Label><br />

        <br />

        <br />

        <br />

    </div>

    </form>

</body>

</html>

.CS code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Data;

 

public partial class DetailPage : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (Page.RouteData.Values["id"].ToString() != null)

        {

            string strId = Page.RouteData.Values["id"].ToString();

            DisplayArticle(strId);

 

        }

    }

 

    private void DisplayArticle(string strId)

    {

        string strConn = ("Data Source=.; uid=sa; pwd=Micr0s0ft; database=TestDB");

        SqlConnection conn = new SqlConnection(strConn);

        SqlDataAdapter da = new SqlDataAdapter("select Id,Title,Description,author from Articletable where Id=" + strId, conn);

        DataSet ds = new DataSet();

        da.Fill(ds, "Articletable");

        lblTitle.Text = ds.Tables["Articletable"].Rows[0][1].ToString();

        lblDescription.Text = ds.Tables["Articletable"].Rows[0][2].ToString();

        lblauthor.Text = ds.Tables["Articletable"].Rows[0][3].ToString();

 

    }

}

 

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