【问题标题】:How to use more than 1 Model on a page by using asp.net mvc 5?如何使用 asp.net mvc 5 在页面上使用多个模型?
【发布时间】:2015-06-10 16:02:01
【问题描述】:

我想使用 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上)。

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

【问题讨论】:

  • 对于您的特殊情况Action(controller:login, action:ChildActionShowLinks ...) 可能会更好地封装视图...有关更多建议/讨论,请参阅stackoverflow.com/questions/4154407/…
  • 创建一个包含两个模型的连接视图模型,然后将其传递给您的控制器?
  • @DarkBobG 我不认为它可以解决我的问题。因为如果您创建一个包含 2 个child modelsparent model,它应该可以工作。但是如果我从另一个操作中引用 _Layout.cshtml 会发生什么?
  • 点赞:public ActionResult AnotherAction() { OtherModel model = new OtherModel(); return View(model); }

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


【解决方案1】:

在您的布局中使用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);
}

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

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

【讨论】:

    【解决方案2】:

    更好的方法是使用局部视图和 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)
    

    【讨论】:

    • 您的意思是:使用 ViewBag 登录?如果您进行新的重定向,ViewBag 数据将丢失。但我会回想ViewBag.HomePage。谢谢。
    • 你不应该把模型放在你的 _Layout.cshtml 中。您应该将它们放入您的视图或部分视图中,因为您的所有页面都使用 _Layout.cshtml。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多