视图模型排序?

时间:2017-05-18 23:47:19

标签: c# asp.net-mvc-5 asp.net-core entity-framework-core visual-studio-2017

我有一个视图模型,它结合了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);
    }

如何为此视图模型添加排序功能?我想按VendorName&amp; LASTUPDATEDATE。我在这里关注本教程:https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page。它不适用于我的视图模型,因为我只能对供应商信息进行排序。我想排序促销,联系人和经销商信息。

2 个答案:

答案 0 :(得分:0)

我会使用.Order By(...)在tolistasync调用之前的原始查询

答案 1 :(得分: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));

当您对要在另一个集合上执行的一个集合上执行操作时,您只需对该另一个集合执行相同的操作。这些陈述不会以某种方式相互嵌套。