c# - 如何将 Dictionary 绑定(bind)到 ASP.NET MVC 5 Razor 模板引擎中的部分 View

标签 c# asp.net asp.net-mvc razor asp.net-mvc-5

我有以下演示类(class)

public class CustomerReportPresentation
{
    public ReportFormat ReportFormat { get; set; }

    public List<Dictionary<string, object>> Data { get; set; }
}

在 Controller 中我有以下代码

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);

现在,在我相应的 View 中,我有以下代码

@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)
}

我正在将列表传递给部分 View 。然后每个部分 View 都会以不同的方式显示数据。

这是我的部分观点

@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在部分。删除Data从最后Model 。奇怪的是,智能感知没有警告你 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>

这意味着您从 View 发送的部分接收的模型不是 CustomerReportPresentation但参数Data Model

// 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)

关于c# - 如何将 Dictionary 绑定(bind)到 ASP.NET MVC 5 Razor 模板引擎中的部分 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38361361/

相关文章:

c# - 是否有一种可移植的方式来表示任意数据库表(结构仅在运行时已知),类似于 DataSet/DataTable 的方式?

c# - 通过字符串 na C# 实例化子类

asp.net - 如何禁用连接到服务器事件的asp.net ImageButton(因此无法重新发布)

asp.net 3.5 设置自定义 web 控件中控件的样式

c# - 尝试将 SQL 中的 varbinary(MAX) 值转换为 byte[] 并在 asp 图像控件中显示

asp.net-mvc - MVCScaffoliding 包抛出 MethodInvocationException

c# - 如何使用最新版本的 C# (1.8.2+) 驱动程序获取 MongoCursorEnumerator<T>?

c# - 如果没有 GetAwaiter 方法,我可以 await 吗?

asp.net-mvc - StackExchange.Redis.IDatabase存在于两个dll中

c# - 我的 FormsAuthenticationTicket 做错了什么?