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

本文关键字:一个 模型 mvc net asp 何使用 | 更新日期: 2023-09-27 17:54:53

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

在包含动作public ActionResult Index(){...}的控制器中,我声明了一些值并将其返回给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 model),但我想渲染的一些值是从MyProjectName.Models.LoginModel

引用的

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

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

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

在您的布局中使用Html.Action()Html.RenderAction()调用ChildActionOnly方法,该方法返回LoginModel的部分视图

[ChildActionOnly]
public ActionResult Login()
{
  LoginModel model = // initialize the model you want to display in the Layout
  return PartialView(model);
}
并创建一个显示链接的部分视图,然后在Layout 中
@ { Html.RenderAction("Login", "yourControllerName") }

一个更好的方法是使用部分视图和ViewBag。

在控制器的

中你会做类似的事情:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Accounts = new AccountsViewModel();
        ViewBag.HomePage = new HomePageViewModel();
        return View();
    }
}

从这里你将你的模型从ViewBag传递到一个局部视图

@{
    AccountViewModel Accounts = (AccountViewModel)ViewBag.Accounts;
}
@Html.Partial("_accountPartial", Accounts)