-1

我有一個視圖模型,結合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。它不適用於我的視圖模型,因爲我只能對供應商信息進行排序。我想排序促銷,聯繫&分銷商信息以及。

+0

你想排序什麼? – WellerEE

+0

你通常會用'.OrderBy()'對一個集合進行排序。 「它不適用於視圖模型」是什麼意思?你嘗試了什麼,它是如何失敗的? – David

+0

@WellerEE名稱和日期 –

回答

0

不能確定你要在這裏做什麼之前:

viewModel.Vendors = viewModel.Vendors.OrderBy(i => i.Distributors.OrderBy(v => v.LastUpdateDate)); 

的是語義對我來說真的沒有意義,我相信編譯器也同樣困惑。您是否想要對VendorsDistributors集合進行排序?這將是兩個單獨的排序操作。事情是這樣的:

viewModel.Vendors = viewModel.Vendors.OrderBy(i => i.LastUpdateDate)); 
viewModel.Distributors = viewModel.Distributors.OrderBy(v => v.LastUpdateDate)); 

當你有,你要到另一個集合執行一個集合的操作,你只是做給其他集合同樣的事情。這些陳述不會以某種方式嵌套在一起。

0

我會用.Order通過(...)在我原來的查詢tolistasync調用