Search code examples
asp.net-mvcpaginationasp.net-mvc-routing

How do I implement paging on a route with other parameters?


I know how to implement paging on a route when there's a single route such as /Dinners/Page/1. My issue is that I have a list of articles. These articles are sat in categories and subcategories.

If no category/subcategory is specified I want to return all articles. If only category is supplied I supply all articles in that category If category and subcategory are supplied I want only the articles in the subcategory.

I had this working no problem. Then I wanted to add paging. I wanted a route that could do the following: domain.com/6 - goes to page 6 of all articles domain.com/category/2 - goes to page 2 of category articles domain.com/category/subcategory/3 - goes to page 3 of subcategory articles

I can't get this working because the first example is looking for category 6, the second is looking for category 2. I've tried adding a constraint in the hope the numeric value would be attributed to page. No joy.

Also, I want to do this server side.

Any ideas? Here's the route in my RouteConfig:

   routes.MapRoute(
                name: "Category",
                url: "{category}/{subcategory}/{page}",
                defaults: new { controller = "Articles", action = "Index", category= UrlParameter.Optional, subcategory = UrlParameter.Optional, page = UrlParameter.Optional }
                //, constraints: new { page = @"\d+" }
            );

Solution

  • Ok. I played around with the route and added three routes to replace the original.

    The first one captures the view all with the paging. If no paging is provided I just display the first page. The second route is the main category with paging.

    The third route covers off if there is a subcategory. This is working like a charm now. :)

    Here are my routes in case you want to know exactly what I did:

            routes.MapRoute(
                name: "Paged",
                url: "{page}",
                defaults: new { controller = "Articles", action = "Index", page = UrlParameter.Optional }, 
                constraints: new { page = @"\d+" }
            );
    
            routes.MapRoute(
                name: "PagedCategory",
                url: "{category}/{page}",
                defaults: new { controller = "Articles", action = "Index", category = UrlParameter.Optional, page = UrlParameter.Optional }
                //, constraints: new { page = @"\d+" }
            );
    
            routes.MapRoute(
                name: "PagedSubCategory",
                url: "{category}/{subcategory}/{page}",
                defaults: new { controller = "Articles", action = "Index", category = UrlParameter.Optional, subcategory = UrlParameter.Optional, page = UrlParameter.Optional }
                //, constraints: new { page = @"\d+" }
            );