public IActionResult Index() { try { IEnumerable <AnimalListingViewModel> animals = _animalService.GetAll() .Select(animal => new AnimalListingViewModel { Id = animal.Id, Name = animal.Name, Age = animal.Age, Gender = animal.Gender, Species = animal.Species, Breed = animal.Breed, Color = animal.Color, AnimalRestrictions = animal.AnimalRestrictions, Media = animal.Media }); var model = new AnimalIndexViewModel { AnimalList = animals }; return(View(model)); } catch (Exception ex) { ErrorViewModel error = new ErrorViewModel(); error.Message = ex.Message; return(RedirectToAction("Error", "Home", error)); } }
public ActionResult Index(string category, string search, string sortBy, int?page) { //instantiate a new view model AnimalIndexViewModel viewModel = new AnimalIndexViewModel(); //select the Animals var Animals = db.Animals.Include(p => p.Category); //perform the search and save the search string to the viewModel if (!String.IsNullOrEmpty(search)) { Animals = Animals.Where(p => p.Name.Contains(search) || p.Description.Contains(search) || p.Category.Name.Contains(search)); viewModel.Search = search; } //group search results into categories and count how many items in each category viewModel.CatsWithCount = from matchingAnimals in Animals where matchingAnimals.CategoryID != null group matchingAnimals by matchingAnimals.Category.Name into catGroup select new CategoryWithCount() { CategoryName = catGroup.Key, AnimalCount = catGroup.Count() }; if (!String.IsNullOrEmpty(category)) { Animals = Animals.Where(p => p.Category.Name == category); viewModel.Category = category; } //sort the results switch (sortBy) { case "name": Animals = Animals.OrderBy(p => p.Name); break; case "name_rev": Animals = Animals.OrderByDescending(p => p.Description); break; default: Animals = Animals.OrderBy(p => p.Name); break; } int currentPage = (page ?? 1); viewModel.Animals = Animals.ToPagedList(currentPage, Constants.PageItems); viewModel.SortBy = sortBy; viewModel.Sorts = new Dictionary <string, string> { { "Name", "name" }, { "Description", "name_rev" } }; return(View(viewModel)); }