我的_Layout
页面在几个点使用@RenderSection
,例如渲染侧边栏(如果有的话)。我有大约30种不同的视图,它们使用10种不同的模型来获取内容。但是目前只有4个不同的侧边栏,所以我把它们分成了这样调用的部分视图:
@section SBLeft {
@Html.Partial("_SidebarTopics)
}
这在我的首页上运行正常,因为从_SidebarTopics
视图调用的侧边栏部分Frontpage\Index.cshtml
使用在索引视图开头调用的相同模型(WebsiteStructureModel
) :
@model Web.Areas.Public.Models.WebsiteStructureModel
现在我遇到问题,当我想使用一个使用模型A的侧边栏时,如果"父母" view使用Model B.导致如下错误:
The model item passed into the dictionary is of type 'Web.Areas.Public.Models.ProjectDetailsModel', but this dictionary requires a model item of type 'Web.Areas.Public.Models.WebsiteStructureModel'.
在Index视图的开头使用两个@model
语句不起作用,因此我无法将第二个模型明确地作为@Html.Partial
命令的第二个参数传递给侧栏。在部分视图开头使用@model
语句将被忽略。
必须有某种方法来调用局部视图,并使该局部视图使用指定的模型,该模型可能不一定是调用/父视图使用的模型 - 请帮助我理解如何做到这一点!
答案 0 :(得分:3)
有两种方法可以做到这一点。
您可以将2个模型组合成视图模型:
public class ViewModel
{
public WebsiteStructureModel WebModel { get; set; }
public ProjectDetailsModel ProjectModel { get; set; }
}
您显然会在Action
中填充此内容,然后将其传递给视图
您可以在控制器中创建@Html.Partial("_SidebarTopics")
而不是调用Action
,return PartialView("_SidebarTopics", model);
model
其中@section SBLeft {
@Html.Action("SidebarTopics", new { /* route params */ });
}
是传递到局部视图的模型,例如:
public ActionResult SidebarTopics(/* route params */)
{
var model = new ProjectDetailsModel();
return PartialView("_SiderbarTopics", model);
}
控制器:
{{1}}