2011-05-11 89 views
0

我想訂購一些基於價格的產品。我傳遞給我的動作的參數是什麼?我如何使用它從IQueryable<Product>進行排序?asp.net mvc根據控制器中的參數訂購商品

例如,這是我目前有:

public ActionResult Index(int page =0, int cat = 0, int subCat =0) 
    { 
     var products = productService.GetAllProducts(); 

     ProductListViewModel model = new ProductListViewModel(); 

     if (cat > 0) 
     { 
      products = products.Where(p => p.SubCategory.CategoryId == cat); 
     } 
     if (subCat > 0) 
     { 
      products = products.Where(p => p.SubCategory.SubCategoryId == subCat); 
     } 

     products = products.OrderBy(p => p.CreatedDate); 

     model.PagedProducts = products.ToPagedList(page, 15); 
     return View(model); 
    } 
+0

如果你只是想按價格排序,在行動中不應該有任何需要通過的東西 - 你是否試圖篩選到潛艇?等產品的基礎上的一些參數? – ataddeini 2011-05-11 16:36:54

+0

我在我的頁面上有兩個網址,一個表示按最高價格排序,另一個表示最低價格優先。 – 2011-05-11 16:43:02

回答

1

您可以傳遞任何你想要的變量。一個int應該足夠了,但是你也可以使用一個字符串。

public ActionResult Index(int page =0, int cat = 0, int subCat =0, int order = 0) 
{ 
    var products = productService.GetAllProducts(); 

    ProductListViewModel model = new ProductListViewModel(); 

    if (cat > 0) 
    { 
     products = products.Where(p => p.SubCategory.CategoryId == cat); 
    } 
    if (subCat > 0) 
    { 
     products = products.Where(p => p.SubCategory.SubCategoryId == subCat); 
    } 

    switch(order) 
    { 
     case 0: 
      products = products.OrderBy(p => p.CreatedDate); 
      break; 
     case 1: 
      products = products.OrderBy(p => p.Price); 
      break; 
    } 

    model.PagedProducts = products.ToPagedList(page, 15); 
    return View(model); 
} 
0

更換

products = products.OrderBy(p => p.CreatedDate); 

products = products.OrderBy(p => p.Price); 
0

如果您在傳遞一個bool標誌,那麼,你可以用它來切換排序:

public ActionResult Index(int page, int cat, int subCat, int order, bool isAscending) 
{ 
    var products = productService.GetAllProducts(); 

    if (isAscending) 
     products = products.OrderBy(prod => prod.Price); 
    else 
     products = products.OrderByDescending(prod => prod.Price); 

    // Other code... 
}