I have a view model that combines data from 3 models.
public class VendorVM
{
public IEnumerable<Vendor> Vendors { get; set; }
public IEnumerable<Promo> Promos { get; set; }
public IEnumerable<Contact> Contacts { get; set; }
public IEnumerable<Distributor> Distributors { get; set; }
}
Here's the controller:
public async Task<IActionResult> Index(int? id)
{
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
var viewModel = new VendorVM();
viewModel.Vendors = await _context.Vendors
.Include(i => i.Promos)
.Include(i => i.Contacts)
.Include(i => i.Distributors)
.AsNoTracking()
.ToListAsync();
if (id != null)
{
ViewData["VendorID"] = id.Value;
Vendor vendorVM = viewModel.Vendors.Where(
i => i.VendorID == id.Value).Single();
viewModel.Promos = vendorVM.Promos.ToList();
viewModel.Contacts = vendorVM.Contacts.ToList();
viewModel.Distributors = vendorVM.Distributors.ToList();
switch(sortOrder)
{
case "name_desc":
viewModel.Vendors = viewModel.Vendors.OrderByDescending(i => i.VendorName);
break;
case "Date":
viewModel.Vendors = viewModel.Vendors.OrderBy(i => i.Distributors.OrderBy(v => v.LastUpdateDate));
break;
case "date_desc":
viewModel.Vendors = viewModel.Vendors.OrderByDescending(i => i.Distributors.OrderByDescending(v => v.LastUpdateDate)));
break;
default:
viewModel.Vendors = viewModel.Vendors.OrderBy(i => i.VendorName);
break;
}
return View(viewModel);
}
How can I add sorting functionality to this view model? I want to sort by VendorName & LastUpdateDate. I'm following this tutorial here: https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page. It doesn't work for my view model as I can only sort Vendors info. I would like to sort promos, contacts & distributors info as well.
Not really sure what you're trying to do here:
viewModel.Vendors = viewModel.Vendors.OrderBy(i => i.Distributors.OrderBy(v => v.LastUpdateDate));
The semantics of that don't really make sense to me, and I'm sure the compiler is equally confused. Are you trying to sort both the Vendors
and the Distributors
collections? That would be two separate sorting operations. Something like this:
viewModel.Vendors = viewModel.Vendors.OrderBy(i => i.LastUpdateDate));
viewModel.Distributors = viewModel.Distributors.OrderBy(v => v.LastUpdateDate));
When you have an operation on one collection that you want to perform on another collection, you just do the same thing to that other collection. These statements don't somehow nest into one another.