asp.net-mvc - 局部 View 中不同模型类型的问题

标签 asp.net-mvc asp.net-mvc-3 partial-views

我有一个( Razor )页面,其中包含 5 个不同的局部 View 。每个局部 View 负责来自数据库的一些数据。在那个母版页中,我使用了一个模型对象,但对于部分 View ,我使用了不同的模型对象。问题是,当我在部分 View 中设置模型对象时,我的应用程序因以下错误而中断:
传入字典的模型项的类型是 'MyProject.WebUI.Models.BigPageViewModel', but this dictionary requires a model item of type 'MyProject.WebUI.Models.StatisticsViewModel'.
这是代码:
这是包含部分 View 的大页面:

@model MyProject.WebUI.Models.BigPageViewModel
@{
    Layout = "../Shared/_BigPage.cshtml";
}
...
@{Html.RenderPartial("../Data/StatisticsFeed");}
...

这是 Controller 代码。对于这种方法,我创建了应该在大页面中呈现的部分 View 。
public ActionResult StatisticsFeed()
        {
            StatisticsViewModel cs = new StatisticsViewModel();
            cs.TotalData = (new StatisticsRepository()).GetStatisticCompleteData(1);
            return View(cs);
        }

这是部分 View 中的代码:
@model MyProject.WebUI.Models.StatisticsViewModel
...

enter image description here

我使用了“RenderAction”方法而不是“RenderPartial”,它返回值但返回两个结果,一个有数据,一个没有,这一定是一些愚蠢的错误......
public ActionResult StatisticsFeed()
        {
          StatisticsViewModel cs = new StatisticsViewModel();
                cs.TotalData = (new StatisticsRepository()).GetStatisticCompleteData(1);

            cs.TotalCitizns = 569;
            return View(cs);
        }

最佳答案

您需要使用 RenderPartial 的第二个参数明确指定传递给部分的模型。方法。如果您不指定它,则传递父模型,因此您会得到异常:

@{Html.RenderPartial("../Data/StatisticsFeed", Model.SomePropertyOfTypeStatisticsViewModel);}

另一种可能性是使用 RenderAction :
@{Html.RenderAction("StatisticsFeed", "ControllerName");}

这将调用 StatisticsFeed Controller 操作本身将从数据库中获取模型并呈现结果。

关于asp.net-mvc - 局部 View 中不同模型类型的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7292590/

相关文章:

asp.net-mvc-3 - 设置 Html.DropdownList 的默认值和 CSS 类

json - 通过 http GET 向服务器发送 JSON 对象

ruby-on-rails - 如何不对应用程序中的特定页面使用 application.html.erb 文件?

asp.net-mvc-3 - ASP.NET MVC 3 局部 View 模板

c# - MVC 5 C#将错误报告回数据库

c# - 在 .NET MVC 中,我们可以将 CSS 保留在 Views 文件夹中吗?

javascript - 无法使用 HTML5 File API 和 ASP.NET MVC4 在服务器端捕获文件上传

c# - RedirectToAction 没有按预期刷新页面

asp.net - 如何使用 mvc 中的自定义成员身份添加更多自定义字段?

javascript - 如何刷新div而不重新加载整个页面?