如何将字典绑定到 ASP.NET MVC 5 Razor 模板引擎中的部分视图
本文关键字:引擎 视图 Razor 字典 绑定 MVC NET ASP | 更新日期: 2023-09-27 17:56:45
我有以下演示课
public class CustomerReportPresentation
{
public ReportFormat ReportFormat { get; set; }
public List<Dictionary<string, object>> Data { get; set; }
}
在控制器中,我有以下代码
CustomerReportPresentation customerReport = new CustomerReportPresentation();
customerReport.Data = ReportModel.Get(); // This will return a list like this List<Dictionary<string, object>>
customerReport.ReportFormat = ReportFormat.Tabular;
return View(customerReport);
现在,在我的相应视图中,我有以下代码
@model Project1.Areas.Test.Presentation.CustomerReportPresentation
@{
ViewBag.Title = "Index";
}
@if (Model.ReportFormat == Project1.Support.ReportsGenerator.Report.Contracts.ReportFormat.Summary)
{
@Html.Partial("~/Support/ReportsGenerator/Views/Summary.cshtml", Model.Data)
}
else
{
@Html.Partial("~/Support/ReportsGenerator/Views/Tabular.cshtml", Model.Data)
}
我正在将列表传递给部分视图。然后,每个分部视图将以不同的方式显示数据。
这是我的部分观点
@model List<Dictionary<string, Object>>
<ul>
@foreach (var attributes in Model.Data)
{
<li>
@foreach (var attribute in attributes)
{
@attribute.Value; <text> </text>
}
</li>
}
</ul>
但是当我运行我的项目时,我收到此错误
Compiler Error Message: CS0103: The name 'model' does not exist in the current context
如何解决此问题?
您将Model.Data
发送到部分,然后尝试访问部分中的Model.Data
。从最后一个Model
中删除Data
。奇怪的是,智能感知没有警告你Model.Data
不存在List<Dictionary<string, Object>>
@model List<Dictionary<string, Object>>
<ul>
@foreach (var attributes in Model)
{
<li>
@foreach (var attribute in attributes)
{
@attribute.Value; <text> </text>
}
</li>
}
</ul>
这意味着您从视图发送的模型(在部分上接收的模型不是CustomerReportPresentation
而是Model
的参数Data
// At the end you sendt Model.Data, that means the Data object is recieved by the Partial
@Html.Partial("~/Support/ReportsGenerator/Views/Summary.cshtml", Model.Data)