我有一個視圖模型,結合3個模型的數據。查看模型的排序?
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; }
}
這裏的控制器:
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);
}
我怎樣才能添加排序功能,這個視圖模型?我想按供應商名稱排序& LastUpdateDate。我在這裏按照這個教程:https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page。它不適用於我的視圖模型,因爲我只能對供應商信息進行排序。我想排序促銷,聯繫&分銷商信息以及。
你想排序什麼? – WellerEE
你通常會用'.OrderBy()'對一個集合進行排序。 「它不適用於視圖模型」是什麼意思?你嘗試了什麼,它是如何失敗的? – David
@WellerEE名稱和日期 –