views:

222

answers:

1

I am following Martijn Boland's 'Paging with ASP.NET MVC'. And while helpful it has raised a couple of issues I don't understand.

Martijn says:

Internally, the pager uses RouteTable.Routes.GetVirtualPath() to render the url’s so the page url’s can be configured via routing to create nice looking url’s like for example ‘/Categories/Shoes/Page/1′ instead of ‘/Paging/ViewByCategory?name=Shoes&page=1′.

This is the is what he is talking about:

private string GeneratePageLink(string linkText, int pageNumber)
  {
   var pageLinkValueDictionary = new RouteValueDictionary(this.linkWithoutPageValuesDictionary);
   pageLinkValueDictionary.Add("page", pageNumber);
   //var virtualPathData = this.viewContext.RouteData.Route.GetVirtualPath(this.viewContext, pageLinkValueDictionary);
   var virtualPathData = RouteTable.Routes.GetVirtualPath(this.viewContext.RequestContext, pageLinkValueDictionary);

   if (virtualPathData != null)
   {
    string linkFormat = "<a href=\"{0}\">{1}</a>";
    return String.Format(linkFormat, virtualPathData.VirtualPath, linkText);
   }
   else
   {
    return null;
   }
  }

How does this work? When I use it virtualPathData.VirtualPath just brings back a url representing the first route in my routing table with a 'page' param on the end rather then a url representing the current context.

Also what would the routing look like to change this ‘/Paging/ViewByCategory?name=Shoes&page=1′ to this ‘/Categories/Shoes/Page/1′ ?

A: 

I assume You have Paging controller and this controller has ViewByCategory action.

ViewByCategory looks like:

public ActionResult ViewByCategory(string categoryName, int? page)
{
  ....
}

Routing will look like

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "RouteByCategory",
        "Categories/{categoryName}/Page/{page}",
        new { controller = "Paging", action = "ViewByCategory" }
    );

    routes.MapRoute(
        "RouteByCategoryFirstPage",
        "Categories/{categoryName}",
        new { controller = "Paging", action = "ViewByCategory", page = 1 }
    );

    routes.MapRoute(
        "Default",                                              // Route name
        "{controller}/{action}/{id}",                           // URL with parameters
        new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
    );
}

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
}

GeneratePageLink will return link in ‘/Categories/Shoes/Page/1′ format, because it is first matching route pattern in routing table.

LukLed