public ActionResult Index(ArticlesAdminSearchModel searchModel) { if (searchModel.FromPrice != null && searchModel.ToPrice != null) { if (searchModel.FromPrice >= searchModel.ToPrice) { ModelState.AddModelError("ToPrice", Errors.GreaterThan); return(View("SearchArticles", searchModel)); } } var articles = SearchByCriterias(searchModel); if (searchModel.PageNumber == 0) { searchModel.PageNumber = 1; } var numberOfPages = Math.Ceiling((double)articles.Count() / PageSize); var articlesToDisplay = articles .OrderBy(article => article.Price) .Select(ArticlesListViewModel.FromArticle) .Skip((searchModel.PageNumber - 1) * PageSize).Take(PageSize).ToList(); ViewBag.Pages = numberOfPages; ViewBag.CurrentUrl = Request.Url.AbsoluteUri; AddSearchCriterias(searchModel); return(View(articlesToDisplay)); }
/// <summary> /// Add the search criterias to the ViewBag /// </summary> /// <param name="searchModel">The object that contains the criterias</param> private void AddSearchCriterias(ArticlesAdminSearchModel searchModel) { ViewBag.FromPrice = searchModel.FromPrice; ViewBag.ToPrice = searchModel.ToPrice; ViewBag.CategoryId = searchModel.CategoryId; ViewBag.SearchSubstirng = searchModel.SearchSubstring; ViewBag.PageNumber = searchModel.PageNumber; ViewBag.IsTopArticle = searchModel.IsTopArticle; }
private IQueryable <Article> SearchByCriterias(ArticlesAdminSearchModel searchModel) { var articles = Data.Articles.All(); if (searchModel.CategoryId != null) { articles = articles.Where(article => article.CateoryId == searchModel.CategoryId); //We check if the user gave us incorrect category id if (articles.Count() == 0) { CheckIfCategoryExists((int)searchModel.CategoryId); } } if (articles.Count() != 0 && searchModel.IsTopArticle != null) { articles = articles.Where(article => article.IsSelectedForTopArticle == searchModel.IsTopArticle); } if (articles.Count() != 0 && searchModel.FromPrice != null) { articles = articles.Where(article => article.Price >= searchModel.FromPrice); } if (articles.Count() != 0 && searchModel.ToPrice != null) { articles = articles.Where(article => article.Price <= searchModel.ToPrice); } if (articles.Count() != 0 && !string.IsNullOrWhiteSpace(searchModel.SearchSubstring)) { articles = articles .Where(article => article.NameBg.Contains(searchModel.SearchSubstring) || article.NameEn.Contains(searchModel.SearchSubstring)); } return(articles); }