How to use more than 1 model per page using asp.net mvc 5?

I want to use 2 models. The first is on the page Index.cshtml

and the second is on the page_Layout.cshtml

In the controller that contains the action public ActionResult Index(){...}

, I declare some values ​​and return them to View (). Like this:

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

      

And in MyProjectName.Models

I am writing some classes to check the account and put it on the page _Layout.cshtml

. Like this:

On the page _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" })
   }
}

      

The code on the page _Layout.cshtml

doesn't work. He said that: I returned a model ( HomePageViewModel model

), but some of the values ​​I want to display refer toMyProjectName.Models.LoginModel

Basic requirement: the first model is used to display content on the page Index.cshtml

, and the second model is used to validate user login (on the page _Layout.cshtml

).

Can you tell me how to do this? Thank!

+3


source to share


2 answers


In your layout, use Html.Action()

or Html.RenderAction()

to call a method ChildActionOnly

that returns a partial view forLoginModel

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

      



and create a partial view showing links then in layout

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

      

+1


source


The best approach would be to use Partial Views and ViewBag.

in your controller, you would do something similar to this:

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

        return View();
    }
}

      



From here you can pass your model from ViewBag to partial view

@{
    AccountViewModel Accounts = (AccountViewModel)ViewBag.Accounts;
}

@Html.Partial("_accountPartial", Accounts)

      

0


source







All Articles