【问题标题】:Problem with different model type in partial view局部视图中不同模型类型的问题
【发布时间】:2011-09-03 10:34:13
【问题描述】:

我有一个(剃刀)页面,其中包含 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");}
...

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

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

这是部分视图中的代码:

@model MyProject.WebUI.Models.StatisticsViewModel
...

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    另一种可能是使用RenderAction:

    @{Html.RenderAction("StatisticsFeed", "ControllerName");}
    

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

    【讨论】:

    • 所以我的“bigPage”模型对象中需要有“Statistic”对象属性?
    • @1110,是的。好吧,您必须将StatisticsViewModel 的实例传递给您的部分,因为这是它所期望的。在哪里存储它是另一个问题。它确实可能是您的主视图模型上的一个属性。您也可以传递一个新实例:new StatisticsViewModel().
    • 如果我传递新对象,则该对象为空。在我的问题的第二个代码中,我填充了具有该部分视图数据的对象。当我在“bigPage”模型中有统计对象时,我的问题就解决了。所以我无法在部分视图中直接从控制器注入?因为我怕我的 'bigPageViewModel' 太大了。
    • @1110,您可以使用 RenderAction 代替 RenderPartial,如下所示:@{Html.RenderAction("StatisticsFeed", "ControllerName");}。这将通过控制器操作并渲染部分。我也更新了我的答案以包含一个示例。
    • 谢谢我不知道 RenderAction 并且我接近结果,因为我收到了值:)。但是我现在收到两个结果,一个有数据,一个没有,我已经更新了问题,你能检查一下我的代码中有一些小错误吗?
    猜你喜欢
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多