局部视图中不同型号的问题

111*_*110 5 asp.net-mvc partial-views asp.net-mvc-3

我有一个(剃刀)页面,包含5个不同的部分视图.每个局部视图负责来自数据库的一些数据.在该母版页中,我使用一个模型对象,但对于部分视图,我使用不同的模型对象.问题是,当我在局部视图中设置模型对象时,我的应用程序会出现以下错误:传递到字典中的模型项是类型'MyProject.WebUI.Models.BigPageViewModel', but this dictionary requires a model item of type 'MyProject.WebUI.Models.StatisticsViewModel'.

这是代码:这是包含部分视图的大页面:

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

这是控制器代码.对于这个方法,我创建了应该在大页面中呈现的局部视图.

public ActionResult StatisticsFeed()
        {
            StatisticsViewModel cs = new StatisticsViewModel();
            cs.TotalData = (new StatisticsRepository()).GetStatisticCompleteData(1);
            return View(cs);
        }
Run Code Online (Sandbox Code Playgroud)

这是部分视图中的代码:

@model MyProject.WebUI.Models.StatisticsViewModel
...
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我使用'RenderAction'方法而不是'RenderPartial'并返回值,但返回两个结果一个数据,一个没有,这一定是一些愚蠢的错误......

public ActionResult StatisticsFeed()
        {
          StatisticsViewModel cs = new StatisticsViewModel();
                cs.TotalData = (new StatisticsRepository()).GetStatisticCompleteData(1);

            cs.TotalCitizns = 569;
            return View(cs);
        }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 7

您需要使用方法的第二个参数明确指定传递给partial的模型RenderPartial.如果您没有指定它,则会传递父模型,因此会得到以下异常:

@{Html.RenderPartial("../Data/StatisticsFeed", Model.SomePropertyOfTypeStatisticsViewModel);}
Run Code Online (Sandbox Code Playgroud)

另一种可能是使用RenderAction:

@{Html.RenderAction("StatisticsFeed", "ControllerName");}
Run Code Online (Sandbox Code Playgroud)

这将调用StatisticsFeed控制器操作,该操作本身将从数据库中获取模型并呈现结果.

  • @1110,是的。好吧,您必须将 `StatisticsViewModel` 的实例传递给您的部分,因为这是它所期望的。你在哪里存放它是另一个问题。它确实可能是您的主视图模型上的一个属性。您还可以传递一个新实例:`new StatisticsViewModel()`。 (2认同)