Working with URL Routing in ASP.NET Web Forms

Introduction

While developing web sites, at times you require that the URLs being used are not mapped to any physical file. For example, you might be building a blog engine that stores all blog posts in a SQL Server database but while displaying these posts you want URLs to be SEO friendly. In such cases the resource pointed to by the URL has no physical existence. That's where the URL Routing features of ASP.NET come to the rescue. In addition to creating SEO friendly URLs these features also help you render easy to remember URLs. ASP.NET MVC relies heavily on the URL Routing feature. However, it is also possible to use URL Routing in web forms. In this tutorial you will learn just that.

Sample Scenario

As an example let's assume that you want to build a simple blog engine that renders search engine friendly URLs. To illustrate the use of URL routing in web forms you will build three simple web forms as shown in Figures 1, 2 and 3.

Displaying blog post categories
Figure 1: Displaying blog post categories

The first page, ShowCategories.aspx, lists all the blog post categories in a GridView as shown in Figure 1.

Displaying list of blog posts belonging to a category
Figure 2: Displaying list of blog posts belonging to a category

Upon selecting a particular category from the ShowCategories.aspx page you are taken to ShowPostsByCategory.aspx where all blog posts belonging to that category are displayed in a GridView (Figure 2).

Displaying a blog post
Figure 3: Displaying a blog post

Finally, clicking on a blog post title takes you to ShowPost.aspx (Figure 3) where the complete post is displayed.

In a web site not using URL routing you would have used query string parameters to pass category and blog post information and your URLs would have looked something like this :

/ShowPostsByCategory.aspx?name=jquery

/ShowPost.aspx?postid=10

Using the URL routing feature you will render the URLs as shown below:

/categories/jquery

/2011/06/11/01

Notice and compare the URLs shown above carefully. Instead of passing category name as a query string parameter you will be using it as a part of the URL itself (/categories/jquery). Similarly, instead of passing the blog post ID in the query string you make use of <year>/<month>/<day>/<id> pattern for rendering blog post URLs.

Creating a Sample Database

Let's first create a database for our example. Create a new ASP.NET Empty Web Site and add a new SQL Server database in its App_Data folder. Then create a new table named BlogPosts with schema as shown in Figure 4.

Schema of BlogPosts table
Figure 4: Schema of BlogPosts table

The BlogPosts table has a simple structure (a real world blog will have many more columns but this simplified schema is sufficient for the examples in this article) and consists of five columns viz. Id, Title, Content, PublishDate and Category.

Defining Routes

The first step in using URL routing in web forms is to define one or more routes. A route is a URL pattern that is mapped to a handler. In the case of web forms applications, the handler is an .aspx file. You need to tell ASP.NET what pattern the incoming URL will have and to which .aspx file it should be mapped. You define the routes in the Global.asax file. So, add a Global Application Class (Global.asax) to the web site and write the following code in it:

void Application_Start(object sender, EventArgs e) 
{
    RouteTable.Routes.MapPageRoute("Category", "categories/{name}", "~/ShowPostsByCategory.aspx");
    RouteTable.Routes.MapPageRoute("BlogPost", "posts/{year}/{month}/{day}/{id}", "~/ShowPost.aspx");
}

Here, you handled the Application_Start event and added a couple of route definitions. The URL routing related classes are found in the System.Web.Routing namespace and you should import it at the top of the Global.asax file.

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

The RouteTable class is responsible for storing all the route definitions for a web site. The routes are accessible via the Routes collection. The MapPageRoute() method allows you to map a URL pattern with its handler web form. In the above code, you defined two routes - Category and BlogPost - as indicated by the first parameter of the MapPageRoute() method. The second parameter specifies the URL pattern for a particular route and the last parameter indicates a web form (.aspx) that is going to handle the route. The portion of the URL pattern with { and } is dynamic in nature. The above code maps URLs with pattern categories/{name} to ShowPostsByCategory.aspx and posts/{year}/{month}/{day}/{id} to ShowPost.aspx. For all other URLs ASP.NET will look for a physical resource matching the URL.

Using Route URLs

Now, lets develop the ShowCategories.aspx web form (see Figure 1). Drag and drop an SQL Data Source control and a GridView control on the ShowCategories.aspx. Configure the SQL Data Source control to select unique categories from the BlogPosts table.

Retrieving unique Category values
Figure 5: Retrieving unique Category values

The SQL Data Source control you just configured acts as the data source for the GridView control. Add a single Template Field to the GridView and design the template as per the following markup.

<asp:TemplateField HeaderText="Blog Post Categories">
    <ItemTemplate>
        <asp:HyperLink ID="HyperLink7" runat="server" 
         NavigateUrl='<%# Eval("Category","~/categories/{0}") %>' 
         Text='<%# Eval("Category") %>'>
        </asp:HyperLink>
    </ItemTemplate>
</asp:TemplateField>

Notice how the NavigateUrl property of the HyperLink is set. The URL pattern you used in this case is /categories/{name}.

In our example, the hyperlinks to the categories are generated dynamically. However, if you wish to statically specify route URLs you can also use the following markup:

<asp:HyperLink ID="HyperLink1" runat="server" 

NavigateUrl="<%$RouteUrl:name=jquery,routename=Category %>">jQuery</asp:HyperLink>

Here, you used <%$RouteUrl %> expression to construct the route URLs.

Using Route Parameters with Data Source Controls

In the previous section you developed ShowCategories.aspx. The URLs from ShowCategories.aspx are of the form /categories/{name} and will be handled by ShowPostsByCategory.aspx web form. The ShowPostsByCategory.aspx web form also contains a SQL Data Source control and a GridView control. The SQL Data Source control, in this case, needs to extract the category name passed to the web form in the URL. This is accomplished with the help of a RouteParameter. A route parameter can be added to an SQL Data Source Control in the WHERE clause dialog (Figure 6).

Adding a Route Parameter to SQL Data Source control
Figure 6: Adding a Route Parameter to SQL Data Source control

As you can see, Figure 6 filters the BlogPosts table on the basis of Category column and source of category name is a route parameter named - name. The equivalent markup is shown below:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:Database1ConnectionString %>" 
    SelectCommand="SELECT * FROM [BlogPosts] WHERE ([Category] = @Category)">
    <SelectParameters>
        <asp:RouteParameter Name="Category" RouteKey="name" Type="String" />
    </SelectParameters>
</asp:SqlDataSource>

This way the SQL Data Source control will fetch only the blog posts belonging to the category specified in the route URL.

The GridView has a single Template Field as shown below:

<asp:TemplateField HeaderText="Blog Posts By Category">
    <ItemTemplate>
        <asp:HyperLink ID="HyperLink1" runat="server" 
          NavigateUrl='<%# GetUrl(Eval("Id"),Eval("PublishDate")) %>' 
          Text='<%# Eval("Title") %>'>
        </asp:HyperLink>
    </ItemTemplate>
</asp:TemplateField>

Notice how the NavigateUrl property of the HyperLink is set. It passes the Id and PublishDate values to GetUrl() method. The GetUrl() method then forms a URL as per the required pattern (posts/{year}/{month}/{day}/{id}) and assigns it to the NavigateUrl property. The GetUrl() method is shown next.

protected string GetUrl(object id, object pubDate)
{
    DateTime dt = DateTime.Parse(pubDate.ToString());
    int postId = int.Parse(id.ToString());
    RouteValueDictionary parameters = new RouteValueDictionary 
    { { "year", dt.Year }, { "month", dt.Month }, { "day", dt.Day }, { "id", postId } };
    return Page.GetRouteUrl("BlogPost",parameters);
}

The GetUrl() method first converts the supplied Id and PublishDate from object to integer and DateTime data types respectively. It then creates a RouteValueDictionary with all the route parameters. In this case route parameters are - year, month, day and id. The GetRouteUrl() method of the Page object accepts a route name and its parameters and returns the corresponding URL (e.g. /posts/2010/12/15/1).

Accessing Route Parameter Values

In this final section you will develop ShowPost.aspx - the web form that displays a particular blog post. This web form needs to access year, month, day and id route parameters and then fetch a blog post based on them.

Drag and drop three Literal controls on the web form and write the following code in the Page_Load event handler.

protected void Page_Load(object sender, EventArgs e)
{
    int year = Convert.ToInt32(Page.RouteData.Values["year"]);
    int month= Convert.ToInt32(Page.RouteData.Values["month"]);
    int day = Convert.ToInt32(Page.RouteData.Values["day"]);
    int id = Convert.ToInt32(Page.RouteData.Values["id"]);

    DateTime dt = new DateTime(year, month, day);

    DataClassesDataContext db=new DataClassesDataContext();

    var record = from p in db.BlogPosts
                 where p.PublishDate == dt && p.Id ==id 
                 select p;

    foreach (BlogPost temp in record)
    {
        Literal1.Text = "<h1>" + temp.Title + "</h1>";
        Literal2.Text = temp.Content;
        Literal3.Text = "Published on : " + temp.PublishDate.ToString();
    }

}

Notice how the above code retrieves route parameters via the RouteData object. The RouteData object stores values as objects and you need to convert them to the appropriate data type. Based on the year, month and day values a DateTime instance is constructed. A LINQ to SQL query is then executed (you need to add a LINQ to SQL class for the BlogPosts table or else you can also write ADO.NET code yourself) to fetch a blog post for that PublishDate and Id (actually you could have used just the Id value as it is the primary key but just to illustrate the use of all route parameters we are using both the conditions). Finally, the blog post is displayed in the Literal controls.

Once the web forms are developed, run ShowCategories.aspx and navigate to a category. Then pick one blog post and see if it is displayed correctly. Notice the URL pattern in each web form and see how URL routing is mapping the URLs with web forms.

Summary

ASP.NET URL Routing features allow you to use URLs that are not directly mapped to a physical file. A route is a URL pattern that is mapped to a handler such as an .aspx file. You can use the URL routing feature in a web forms application by defining one or more routes in Global.asax and then using classes from System.Web.Routing namespace. The data source controls offer Route Parameters to filter data based on route parameter values. The route URLs can be put statically using RouteUrl expression or programmatically using GetRouteUrl() method. A web form can access route parameters with the help of the RouteData object. Together these features make it easy for you to use search engine friendly and easy to remember URLs in your web form based web sites.



About the Author

Bipin Joshi

Bipin Joshi is a blogger and writes about apparently unrelated topics - Yoga & technology! A former Software Consultant by profession, Bipin has been programming since 1995 and has been working with the .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. He was a well known technology author, trainer and an active member of Microsoft developer community before he decided to take a backseat from the mainstream IT circle and dedicate himself completely to spiritual path. Having embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.

Related Articles

Downloads

Comments

  • Edición Limitada GHD preciosos Set de regalo para la venta en España

    Posted by nuqahc685 on 07/25/2013 08:36pm

    Planchas GHD hacer mucho más que producir suaves, directamente diseños. Su propio estilo ofrece platos curvas y ofertas, por lo tanto, de la misma unidad de diseño que sólo tiene que hacer uso de corregir alguien bloquea también puede poner, cambiar y afluencia. Este particular elimina la necesidad real de una serie de problemáticas Recursos de diseño inodoro abajo encimera. pelo ghd australia claro que mi grupo es algo realmente hija de aspecto sencillo en la vida real. Además de eso, que he implementado ni siquiera tiene que ser un saludable dentro del estilo es mirar a un niño. Ciertamente, contiene los factores alentaron la confianza. Explícitamente, la próxima creación, Marca requerir mucha más confianza. Inicialmente innovador, yo me crié un aspecto visual para incorporar diversos confianza para ayudarle a mí personalmente. [url=http://comprar-ghd.manifo.com/]planchas ghd baratas[/url] Se puede controlar manualmente la temperatura de planchas ghd. Si desea una alta temperatura en contacto con su pelo para que puedas calentar un largo tiempo para alcanzar la temperatura deseada. Usted puede utilizar. Nota: cuando se utiliza el pelo ghd, usted debe ser consciente de su propia seguridad, para evitar ser quemado. Fácil de usar ghd, el pelo bien modelleringsværktøjer.Perfekt reflexión para ayudarle a cambiar su mirada, usted puede encontrar la presentación en línea de DVD de maneras de lograr calor ghd peinados recta paso a paso las instrucciones. Tales prácticas en la enseñanza de usted tan pronto como sea posible familiarizarse con el uso de planchas ghd baratas. [url=http://ghddescuentosonline.npage.de/]planchas ghd[/url] Cabina de cabello es un salón de belleza con sede en Maribyrnong, Australia. También es uno de los principales distribuidores de las marcas más importantes en el cuidado del cabello y la industria de la belleza de la región. Aparte de pelo ghd stand también lleva Babyliss, OPI, Moroccanoil, Redken, American Crew y Paul Mitchell. Servicios Booth Cabello también incluye perforación.

    Reply
  • Fake Oakley Bottle Rocket online shop

    Posted by gjnjtisqq on 07/04/2013 10:41pm

    Replica oakleys ,Oakley sunglasses are one of the best sunglasses in the summer, since it is all summer wear fashion and function. Oakley sunglasses are a good choice for summer wear. A particular style, the essential trend of Oakley glasses, Oakley glasses to maintain the most recent trends and circulation from the glasses for their collection, known as the design. You will be when compared with most girls, simply a have to appreciate the opinion of well-known fashion glasses show. Some small tools, as being a almost Louis Vuitton, is often a special individual clothing and accessories. CheAp OAkley DiSpAtch II ,Oakley now offers other forms of sunglasses like skiing and snowboarding to maintain sports fans to get in the activity to experience a clearer knowledge of sports. In case you have enable you to see a beach during the summer time carnival, marketing and advertising to take into account startingsuch a sunglasses, certainly, a special, is just not a tiny obstacle. Sunglasses with many forms of unique variations of sunglasses within the protective effect of ultraviolet rays, glare, glare isn't the same. Many men and women wear to take glasses, positive outward pull off with one hand with Abstract glasses, so it is susceptible to deformation, loosening. Oakley Outlet ,Oakley sunglasses are fashionable for girls to wear during the summer time, beautiful, if you are worries during the summer time, wearing Oakley sunglasses you're going to get a much better visual experience. Oakley sunglasses are equipped for user safety and comfort. These stylish glasses developed in such a way as to make certain that the frame only inside the nose, and?? In both ears. fake ray ban sunglasses ,Establishment of sunglasses, to guard the eyes from the sun. Oakley is a good pondering cheap Oakley sunglasses for your package away from sales network, and frequently consider what you are able to improve many. Hardly believe you might succeed, if the most people imagine that your move is tantamount to breaks against it, but who are aware that your creation can become a mainstay of certain areas. longchamp pas cher ,Starting from materials to style towards the framework of the production process, every detail perfect, to make the wearer feel comfortable. Beyond just the function of these Oakley sunglasses, other exciting features including high-performance three matching, custom-designed hinge mechanism, facilities plus the facilities on the framework of the ultra-lightweight materials. You'll find a trusted company, providing high-quality products, the lowest cost for the minutes of the greatest pattern, variety, sunglasses add-ons monitor.

    Reply
  • Honest review provides Couple of all new things around nike shoes that no-one is talking about.

    Posted by moisseenfogma on 05/19/2013 02:52am

    M [url=http://www.nikekutuja.biz/]nike running[/url] ctMxg QiaSjs QkiKoo Fie [url=http://www.nikekutuja.biz/air-jordan空気ヨルダン-c-1.html]air jordan[/url] VneLifPxc Kh [url=http://www.nikekutuja.biz/air-maxエアマックス-c-2.html]ナイキ エアマックス[/url] mBgtEogPji XbvYdhQpx [url=http://www.nikekutuja.biz/nike-air-force-1ナイキエアフォース-c-4.html]nike air force 1[/url] Rgv ZkzEvb Mc [url=http://www.nikekutuja.com/]ナイキスニーカー[/url] tAgy LugBrw JcyFmz SssH [url=http://www.nikekutuja.com/air-jordan空気ヨルダン-c-1.html]air jordan[/url] tkZowAfx DqeLerAakZ [url=http://www.nikekutuja.com/nike-dunkナイキダンク-c-4.html]nike store[/url] np DjxUnfRk [url=http://www.nikekutuja.com/air-maxエアマックス-c-2.html]ナイキ エアマoックス[/url] lKbu IagMrc Ru [url=http://www.nikekutujp.com/]ナイキスニーカー[/url] xHog BwxLmp QtnDes ViyU [url=http://www.nikekutujp.com/nike-dunkナイキダンク-c-4.html]nike store[/url] utQekFxp W [url=http://www.nikekutujp.com/nike-air-force-1ナイキエアフォース-c-3.html]ナイキ エアフォース1[/url] dgAuwKyfCcz [url=http://www.nikekutujp.com/air-jordan空気ヨルダン-c-1.html]nike jordan[/url] YgoXixIjnDts EelZhd

    Reply
  • Our intricate assortments of teen clothing and girls clothing means you objective song one's hands on all things to by way of apropos your look.

    Posted by carpitbih on 04/15/2013 11:15pm

    We're not talking run-of-the-mill miserliness vend finds. From beaded [url=http://www.hollistercorfrance.fr]hollister france[/url] floor-length gowns to ostrich feather-adorned fete dresses to one-of-a-kind Christian Dior jackets, the primeval garments [url=http://www.abercrombiesfrancevparise.fr]abercrombie paris[/url] and accessories in the LaBrea Avenue boutique subsume been purchased on A-list celebrities, stylists, designers, and dour superior clothing aficionados who assurance Doris' eye. In between traveling [url=http://www.airjordanfrpaschere.fr]air jordan pas cher[/url] alongside Doris on her out of hunting shopping marathons, the viewer is exposed to communicative tidbits from her full acquaintance of fad annals, a renewal feature that distinguishes the get under way from its superficial, “What Not to Bore”-style genuineness small screen counterparts. We spoke with Doris [url=http://www.abercrombieufrancersoldes.fr]abercrombie france[/url] to learn more hither her passion for the treatment of vintage. What followed was a alms wristband convulsion, a appropriate to [url=http://www.airjordanspasuchere.fr]jordan[/url] way to brandish your bravery on your sleeve, or your cause on your wrist. Silicone gel “awareness bands” were made in all shades of [url=http://www.hollisterfrancevmagesin.fr]hollister france[/url] the rainbow to erect awareness and further support in compensation all types of causes: pink pro boob cancer, purple in the serving of pancreatic cancer, discouraged in behalf of autism, red suitable AIDS, orange for [url=http://www.abercrombievandfitchuks.co.uk]abercrombie uk[/url] anti-smoking. Because a bare buck, you could divulge a harangue of rubber on your wrist and be braceleted, truck yourself a encourage on the sneakily into your [url=http://www.monclerfrancermagasinsfr.fr]doudoune moncler[/url]contribution to making the cosmos a safer place. Minute that we’ve shared Dani + Dominic’s colourful position photos, [url=http://www.airjordanzchaussuren.com]air jordan[/url] it’s measure to dividend their association! I happiness that Dani + Dom made on the brink of the whole seeking their day. Dani is wearing story of my most favorite dresses from [url=http://www.michaelukorsua.com]michael kors outlet[/url] BHLDN and her bridesmaids all wore refulgent dresses from Uncontrolled People. They did all entirely untraditional including calling dick a week foregoing to and changing the ever of their fusing! The two [url=http://www.hollisterucoboutiquer.fr]hollister pas cher[/url] of them passion accepted on thoroughfare trips and because of their uncountable nights on the public roads, “Unconstrained” via Zach Brown Gang became their anthem and earliest skip song [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin[/url].

    Reply
  • Some mbt Shoes or boots May be the Very best Gift For any Those who find themselves Enthusiastic ab

    Posted by mbt shoes on 12/01/2012 03:09am

    It's fairly easy so you might realize that nearly all residents near you are certainly inclined to just one name, known as mbt, as well as their particular items are in some places, that you choose to are unable to refuse. And what is more, the wearer can get wonderful fashion in addition to fashion, and individuals remain to generally be happy with all of these items as we all wish to be wonderful along with excellent. It's now precise for you to know another thing which is mbt is rather victorious today plus their items are also of top quality, that you'll employ a put on.

    Reply
  • just what I need

    Posted by ojorma on 05/05/2012 04:25am

    Wow u're a life saver. If u go through the web especially msdn all the show u is how to do static routes as though is the way we work. Thanks a million. I really needed this for a news site I was developing and wanted a cleaner url.

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

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • 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 …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds