2017-04-16 80 views
2

我有輸入Action方法的問題。MVC輸入操作方法

我有這樣的代碼:

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 } 
    ); 
} 

當I型URL:http://localhost/Page2http://localhost/Page3page_number值總是1。 爲什麼?

回答

1

URL模板中的模板參數需要與Action中的參數名稱匹配。

所以要麼改變配置來匹配動作。

routes.MapRoute(
    name: null, 
    url: "Page{page_number}", 
    defaults: new { Controller = "Product", action = "List" } 
); 

或更改動作相匹配的配置

public ViewResult List(int page = 1) { ... }