public ActionResult Catalog(ProductCatalogViewModel model) { //should send model to the view var catalog = new ProductCatalogViewModel(); // используем Queryable для оптимизации, иначе все продукты загружаются из бд в память var products = productService.GetAsQueryable(); //if the search for was submitted if (model != null) { //map the sent params to created model catalog.SearchOption = model.SearchOption; catalog.SearchQuery = model.SearchQuery; catalog.SortOption = model.SortOption; catalog.SortOrder = model.SortOrder; //searching if (!String.IsNullOrEmpty(catalog.SearchQuery) && !String.IsNullOrWhiteSpace(catalog.SearchQuery)) { if (catalog.SearchOption == ProductCatalogSearchOption.Title) products = products.Where(p => p.Title.ToLower().Contains(catalog.SearchQuery.ToLower())); else products = products.Where(p => p.Description.ToLower().Contains(catalog.SearchQuery.ToLower())); } //sorting if (catalog.SortOption == ProductCatalogSortOption.Title) { if (catalog.SortOrder == ProductCatalogSortOrder.Ascending) products = products.OrderBy(p => p.Title); else products = products.OrderByDescending(p => p.Price); } else { if (catalog.SortOrder == ProductCatalogSortOrder.Ascending) products = products.OrderBy(p => p.Price); else products = products.OrderByDescending(p => p.Price); } } // Используем To list только в конце catalog.Products = ProductMapper.MapProductsToModels(products.ToList()); return View(catalog); }
public ActionResult Catalog(ProductCatalogViewModel model) { //should send model to the view var catalog = new ProductCatalogViewModel(); catalog.Products = ProductMapper.MapProductsToModels(productService.GetAll()); //if the search for was submitted if (model != null) { //map the sent params to created model catalog.SearchOption = model.SearchOption; catalog.SearchQuery = model.SearchQuery; catalog.SortOption = model.SortOption; catalog.SortOrder = model.SortOrder; //searching if (!String.IsNullOrEmpty(catalog.SearchQuery) && !String.IsNullOrWhiteSpace(catalog.SearchQuery)) { if (catalog.SearchOption == ProductCatalogSearchOption.Title) catalog.Products = catalog.Products.Where(p => p.Title.ToLower().Contains(catalog.SearchQuery.ToLower())).ToList(); else catalog.Products = catalog.Products.Where(p => p.Description.ToLower().Contains(catalog.SearchQuery.ToLower())).ToList(); } //sorting if(catalog.SortOption == ProductCatalogSortOption.Title) { if (catalog.SortOrder == ProductCatalogSortOrder.Ascending) catalog.Products = catalog.Products.OrderBy(p => p.Title).ToList(); else catalog.Products = catalog.Products.OrderByDescending(p => p.Price).ToList(); } else { if (catalog.SortOrder == ProductCatalogSortOrder.Ascending) catalog.Products = catalog.Products.OrderBy(p => p.Price).ToList(); else catalog.Products = catalog.Products.OrderByDescending(p => p.Price).ToList(); } } return View(catalog); }