c# - 如何将多个对象从控制器操作传递到 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
作为强类型传递给视图。可能吗 ?
解决方案
为您的视图提供模型类。在该视图中,您引用您的模型类。创建模型类的两个列表属性。请参阅下面的示例:
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);
}
推荐阅读
- java - Netbeans 和 Maven,如何阻止 Maven 尝试下载?
- cython - Cython:我如何知道何时分配对对象的引用或分配具有相同值的对象的副本?
- r - 如何使用ggplot2从具有非等距轴的矩阵绘制等高线图?
- laravel - 通用请求字段的全局定义规则
- java - 在java中并排显示来自磁盘和URL的图片
- javascript - 是的,使用匹配问题使用正则表达式进行验证
- python-3.x - Python 3:函数参数中的省略号?
- excel - VBA将一列的单元格值以数值(MMDD)开头的数据行复制到另一个工作表
- python - 如何在numpy中组合数组?
- angular - 后台同步不会自动触发