c# - 如何使用 asp.net mvc 5 在一个页面上使用多个模型?

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

我想使用 2 个模型。第一个在Index.cshtml页面,第二个在_Layout.cshtml页面

在包含操作 public ActionResult Index(){...} 的 Controller 中,我声明了一些值并将其返回给 View()。像这样:

public ActionResult Index()
{
   HomePageViewModel model = new HomePageViewModel();
   // do something...
   return View(model);
}

MyProjectName.Models 中,我编写了一些类来检查登录帐户并将其放在页面 _Layout.cshtml 上。像这样:

_Layout.cshtml页面上:

@using MyProjectName.Models
@model MyProjectName.Models.LoginModel

@if (Model.LoginAccount != null)
{
   foreach(Account acc in Model.LoginAccount)
   {
      @Html.ActionLink(@acc.Email, "SomeAction", "SomeController", null, new { id = "loginEmail" })
      @Html.ActionLink("Logout", "SomeAction", "SomeController", null, new { id = "logout" })
   }
}

_Layout.cshtml 页面上的代码不起作用。它说:我已经返回了一个模型(HomePageViewModel 模型),但是我想要呈现的一些值是从 MyProjectName.Models.LoginModel

中引用的

主要需求是:第一个模型用于显示页面Index.cshtml上的内容,第二个模型用于检查用户登录(在页面_Layout.cshtml).

你能告诉我怎么做吗?谢谢!

最佳答案

在您的布局中使用 Html.Action()Html.RenderAction() 调用 ChildActionOnly 方法返回部分 View 登录模型

[ChildActionOnly]
public ActionResult Login()
{
  LoginModel model = // initialize the model you want to display in the Layout
  return PartialView(model);
}

并创建一个显示链接的局部 View ,然后在布局中

@ { Html.RenderAction("Login", "yourControllerName") }

关于c# - 如何使用 asp.net mvc 5 在一个页面上使用多个模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30761557/

相关文章:

c# - 关闭 Word 文档时出错 : "The message filter indicated that the application is busy."

c# - 将 System.Double 表示为可排序字符串的最佳方式是什么?

css - Blazor 服务器端使用嵌入样式格式化 MarkupString,同时忽略 Css 文件样式

javascript - 使用动态 HTML 包装 Razor 页面

c# - 使用 TempFileCollection 删除 ASP.NET MVC C# 中的临时文件

c# - C#中用于存储库模型的实体基类设计

c# - 获取列 c# 的首字母

c# - 如何在 ASP.NET MVC 4 区域中正确使用 Html.ActionLink

asp.net-mvc - typescript 捆绑和缩小?

asp.net-mvc-5 - 电子邮件不能为空。 MVC 5,身份2.0.0