如何在不使用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
都作为强类型传递给视图。有可能吗?
答案 0 :(得分:2)
为您的视图提供模型类。在该视图中,您引用模型类。创建模型类的两个列表属性。参见下面的示例:
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);
}
答案 1 :(得分:0)
您应该将这两种类型都包装到某些ViewModel类中,如下所示:
public class CustomerData
{
public List<CustomerDto> Customer { get; set; }
public List<ReportsDto> Reports { get; set; }
}
,然后转到您的视图:
var customerData = new CustomerData()
{
Customer = customersDto,
Reports = reportsDto
}
return View(customerData);
答案 2 :(得分:0)
方法1:
创建一个同时具有属性的视图模型并将该视图模型传递给视图
public class ViewModel
{
public List<CustomerDto> Customers {get;set;}
public List<ReportsDto> Reports {get;set;}
}
方法2:
使用元组并传递该元组对象以查看
var tupleModel = new Tuple<List<CustomerDto>, List<ReportsDto>>(GetCustomers(), GetReports());
return View(tupleModel);
可见
使用Tuple强力键入视图
@model Tuple <List<CustomerDto>, List <ReportsDto>>
使用Item1和Item2属性访问两个对象
@Model.Item1
@Model.Item2