我的 _Layout
页面在几个点上使用了 @RenderSection
,例如渲染侧边栏(如果有的话)。我有大约 30 个不同的 View ,它们使用 10 个不同的模型从中获取内容。但是目前只有 4 个不同的侧边栏,所以我将它们放入局部 View 中,这样调用:
@section SBLeft {
@Html.Partial("_SidebarTopics)
}
这在我的首页上运行良好,因为从 Frontpage\Index.cshtml
View 调用的侧边栏部分 _SidebarTopics
使用相同的模型(WebsiteStructureModel
) 在索引 View 开始时调用:
@model Web.Areas.Public.Models.WebsiteStructureModel
现在,当我想使用使用模型 A 的边栏时,如果“父” View 使用模型 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'.
在索引 View 的开头使用两个 @model
语句不起作用,因此我无法将第二个模型作为 @Html.Partial 的第二个参数显式传递给侧边栏
命令。并且在部分 View 的开头使用 @model
语句将被忽略。
必须有某种方法来调用局部 View 并让该局部 View 使用指定的模型,该模型可能不一定是调用/父 View 使用的模型 - 请帮助我理解如何做到这一点!
最佳答案
有两种方法可以做到这一点。
第一种方式:
您可以将您的 2 个模型组合成一个 View 模型:
public class ViewModel
{
public WebsiteStructureModel WebModel { get; set; }
public ProjectDetailsModel ProjectModel { get; set; }
}
你显然会在你的 Action
中填充它,然后将它传递给 View
第二种方式:
与其调用 @Html.Partial("_SidebarTopics")
,您还可以在 Controller 中创建一个 Action
,它将 返回 PartialView("_SidebarTopics", model );
其中 model
是传入局部 View 的模型,例如:
@section SBLeft {
@Html.Action("SidebarTopics", new { /* route params */ });
}
Controller :
public ActionResult SidebarTopics(/* route params */)
{
var model = new ProjectDetailsModel();
return PartialView("_SiderbarTopics", model);
}
关于c# - asp.net 在部分 View 中使用与其父 View 不同的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22534224/