我跟随
Martijn Boland’s ‘Paging with ASP.NET MVC’.虽然有帮助但它提出了一些我不明白的问题.
Martijn说:
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′.
这就是他所说的:
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; } }
这个怎么用?当我使用它时,virtualPathData.VirtualPath只返回一个url,表示路由表中的第一个路由,最后是一个’page’参数,而不是一个代表当前上下文的url.
此外,路由是什么样的将’/ Paging / ViewByCategory?name = Shoes& page = 1’更改为此’/ Categories / Shoes / Page / 1’?
解决方法
我假设你有Paging控制器,这个控制器有ViewByCategory动作.
ViewByCategory看起来像:
public ActionResult ViewByCategory(string categoryName,int? page) { .... }
路由看起来像
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}",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将以’/ Categories / Shoes / Page / 1’格式返回链接,因为它首先匹配路由表中的路由模式.