我想使用 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/