views:

239

answers:

2

I switched from Intelligencia's UrlRewriter to the new web forms routing in ASP.NET 4.0. I have it working great for basic pages, however, in my e-commerce site, when browsing category pages, I previously used querystrings that were built into my pager control to control paging and now am not sure how to handle this using routing.

I defined a MapPageRoute as:

routes.MapPageRoute("cat-browse", "Category/{name}_{id}", ~/CategoryPage.aspx");

This works great. Now, somebody clicks to go to page 2. Previously I would have just tacked on ?page=2 to the url. How do I handle this using web forms routing? I know I can do something like:

http://www.mysite.com/Category/Arts-and-Crafts_17/page/2

But in addition to page, I can have filters, age ranges, gender, etc.

  1. Should I just keep defining routes that handle these variables like above?
  2. Should I continue using querystrings and if so, how do you define a route to handle that?
A: 

You can take advantage of C# 4.0 named and optional parameters. Please have a look at this example from haacked

If you are using a lower version of the framework, you can also use code from the link above. But instead of declaring the method as

public ActionResult Search(int? page=0)
{}

you can declare it as

public ActionResult Search(int? page)
{
   if(page == null)
   {
     page=0;
   }
}

HTH

jake.stateresa
Jake, I'm not using MVC, I'm using webforms
Scott
+3  A: 

The main reason to use url routing is to expose clean, user-and-SEO-friendly, URLs. If this is your goal, then try to stick to it and not use querystring parameters. Note: I don't believe we need to completely ban the use of querystrings and, depending on your situation, you may decide it best to use querystring parameters for parameters that are not used frequently, or where no real value is added by making the information more semantically meaningful.

So here's what I would do:

Define a catch-all for all your other parameters:

routes.MapPageRoute("cat-browse", "Category/{name}_{id}/{*queryvalues}", "~/CategoryPage.aspx"); 

In /CategoryPage.aspx, access the router parameter and then parse as appropriate:

Page.RouteData.Values["queryvalues"]

Instead of using the syntax of Arts-and-Crafts_17/**page/2/age/34** for these parameters, I perfer to use the following syntax: Arts-and-Crafts_17/pg-2/age-34/

If you do this, the catch-all parameter 'querystring', will equal pg-2/age-34. You can now easily parse this data and add each name/value to the page context. Note that you will need to do something along these lines since each of these parameters are optional on your site.

David A Moss