输入Action方法时遇到问题。
我有这段代码:
public ViewResult List(int page_number = 1) {
ProductsListViewModel model = new ProductsListViewModel {
Products = repository.Products
.OrderBy(m => m.ProductID).Skip((page_number - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo {
CurrentPage = page_number,
ItemsPerPage = PageSize,
TotalItems = repository.Products.Count()
}
};
return View(model);
}
我有这个路线配置:
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: null,
url: "Page{page}",
defaults: new { Controller = "Product", action = "List" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Product", action = "List", id = UrlParameter.Optional }
);
}
当我输入网址时:http://localhost/Page2
或http://localhost/Page3
page_number
的值始终为1
。
为什么呢?
答案 0 :(得分:1)
URL模板中的模板参数需要与Action中的参数名称匹配。
所以要么改变配置以匹配行动。
routes.MapRoute(
name: null,
url: "Page{page_number}",
defaults: new { Controller = "Product", action = "List" }
);
或更改操作以匹配配置
public ViewResult List(int page = 1) { ... }