asp.net mvc根据控制器中的参数订购商品
问题描述:
我想订购一些基于价格的产品。我传递给我的动作的参数是什么?我如何使用它从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);
}
答
您可以传递任何你想要的变量。一个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);
}
答
更换
products = products.OrderBy(p => p.CreatedDate);
与
products = products.OrderBy(p => p.Price);
答
如果您在传递一个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...
}
如果你只是想按价格排序,在行动中不应该有任何需要通过的东西 - 你是否试图筛选到潜艇?等产品的基础上的一些参数? – ataddeini 2011-05-11 16:36:54
我在我的页面上有两个网址,一个表示按最高价格排序,另一个表示最低价格优先。 – 2011-05-11 16:43:02