c# - asp.net 在部分 View 中使用与其父 View 不同的模型?

标签 c# asp.net asp.net-mvc asp.net-mvc-4 razor

我的 _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/

相关文章:

c# - 在 .NET 中可以将数组或列表作为属性返回吗?

c# - 来自当前用户的 PSCredentials

c# - 单击按钮获取 ASP.NET Listview 中项目的 ID

c# - System.Web.HttpException 文件不存在 - 页面加载正常 (ASP.NET)

asp.net-mvc - Asp.net Identity : User. Identity.GetUserId() 始终为 null,User.Identity.IsAuthenticated 始终为 false

c# - 使用 Html.BeginForm 将内容放在结束 </form> 标记之后

c# - 从 JSON 创建数组

c# - 在循环中捕获异步错误

c# - ASP.NET SqlDataSource Gridview 问题

asp.net-mvc - MVC Identity (2.0.1) 中的 regenerateIdentity/validateInterval 持续时间后忽略 ExpireTimeSpan