首页 > 解决方案 > 如何将多个对象从控制器操作传递到 MVC 中的视图?

问题描述

如何在不使用 ViewData 和 ViewBag 的情况下将多个对象传递给视图?

例子:

[AllowAnonymous]
public ActionResult RandomView()
{
   // Customer.
   var customers = _context.Customers.ToList();
   List<CustomerDto> customersDto = new List<CustomerDto>();

   foreach (var customer in customers)
   {
      customersDto.Add(new CustomerDto() { 
      Id = customer.Id,
      Name = customer.Name
      });
   }

   // Reports.
   var Reports= _context.Reports.ToList();
   List<ReportsDto> reportsDto= new List<ReportsDto>();

   foreach (var report in reports)
   {
      reportsDto.Add(new ReportsDto() {
      Id = report.Id,
      Name = report.Name
      });
   }

   return View(); // How to Pass Both CustomerDto and reportDto ?
}

我想将CustomerDto&reportDto作为强类型传递给视图。可能吗 ?

标签: c#asp.net-mvc

解决方案


为您的视图提供模型类。在该视图中,您引用您的模型类。创建模型类的两个列表属性。请参阅下面的示例:

public class RandomViewModel
{
    public List<CustomerDto> Customers { get; set; }
    public List<ReportDto> Reports { get; set; }
}

[AllowAnonymous]
public ActionResult RandomView()
{
   // Customer.
   var customers = _context.Customers.ToList();
   List<CustomerDto> customersDto = new List<CustomerDto>();

   foreach (var customer in customers)
   {
      customersDto.Add(new CustomerDto() { 
      Id = customer.Id,
      Name = customer.Name
      });
   }

   // Reports.
   var Reports= _context.Reports.ToList();
   List<ReportsDto> reportsDto= new List<ReportsDto>();

   foreach (var report in reports)
   {
      reportsDto.Add(new ReportsDto() {
      Id = report.Id,
      Name = report.Name
      });
   }

   var randomViewModel = new RandomViewModel() {
      Customers = customersDto,
      Reports = reportsDto
   };

   return View(randomViewModel);
}

推荐阅读