![](/img/trans.png)
[英]Asp.net MVC search using model and return different model (partial view)
[英]asp.net using a different model in a partial view than in its parent?
我的_Layout
页面在几个点上使用@RenderSection
,例如,渲染侧栏(如果有的话)。 我有大约30种不同的视图,这些视图使用10种不同的模型从中获取内容。 但是,目前只有4个不同的侧边栏,因此我将它们分成部分视图,如下所示:
@section SBLeft {
@Html.Partial("_SidebarTopics)
}
这在我的首页上正常工作,因为从Frontpage\\Index.cshtml
视图调用的侧边栏部分_SidebarTopics
使用与在Index视图的开始处调用的模型相同的模型( WebsiteStructureModel
):
@model Web.Areas.Public.Models.WebsiteStructureModel
现在,当“父”视图使用模型B时,当我想使用使用模型A的边栏时遇到问题。这将导致如下错误:
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'.
在索引视图的开头使用两个@model
语句不起作用,因此我无法将第二个模型作为@Html.Partial
命令的第二个参数显式传递到侧边栏。 在部分视图的开头使用@model
语句将被忽略。
必须有某种方法来调用局部视图,并使该局部视图使用指定的模型,该模型不一定是调用/父视图所使用的模型-请帮助我了解如何做到这一点!
有两种方法可以做到这一点。
您可以将两个模型合并为一个视图模型:
public class ViewModel
{
public WebsiteStructureModel WebModel { get; set; }
public ProjectDetailsModel ProjectModel { get; set; }
}
您显然会在Action
填充它,然后将其传递给“视图”
@Html.Partial("_SidebarTopics")
调用@Html.Partial("_SidebarTopics")
您可以在控制器中创建一个Action
,该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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.