5.1 按照價格對產(chǎn)品進行排序
為了演示如何進行排序,我們將使用一個簡單的例子讓用戶可以對產(chǎn)品按照價格進行排序。
首先,我們向Controllers\ProductsController.cs文件中的Index方法添加一個switch語句,以便可以按照價格對產(chǎn)品信息進行排序,修改之處如下列高亮顯示的代碼:
1 public ActionResult Index(string category, string search, string sortBy) 2 { 3 // instantiate a new view model 4 ProductIndexViewModel viewModel = new ProductIndexViewModel(); 5 6 // select the products 7 var products = db.Products.Include(p => p.Category); 8 9 // perform the search and save the search string to the vieModel10 if (!string.IsNullOrEmpty(search))11 {12 products = products.Where(p => p.Name.Contains(search) || p.Description.Contains(search) || p.Category.Name.Contains(search));13