1

I'm just began new project, using ASP.NET MVC 4, and I have question.

How I may use multiple models (or ViewModel-s) in one view? I'm searched over Internet, and standard solution is "create complex viewmodel with 2 or more properties", e.g.:

public class ComplexViewModel   
{
    public LoginModel LoginModel { get; set; }
    public CartModel CartModel { get; set; }
}

But, for example, in each page I'll have at least 2 model - LoginModel and another model (depends on page). So, I need to define LoginModel in each ViewModel?

P.S.: I'm using ASP.NET MVC 4, Entity Framework 5.

lewis
  • 482
  • 2
  • 10
  • 22
  • 1
    You can use PartialView within your main view, which can contain its own separate model. Perhaps try to research this, there are lots of good tutorials out there – Longball27 Jun 26 '13 at 05:46
  • 1
    If you have the LoginModel in many other models you can create a seperate class for LoginModel and inherit this class in all your other models. – Shai Aharoni Jun 26 '13 at 05:51
  • 1
    You can have base class with those model properties. – Giedrius Jun 26 '13 at 05:51
  • @Longball27, big thnx, I'm used [**this solution**](http://stackoverflow.com/questions/4764011/multiple-models-in-a-view) – lewis Jun 26 '13 at 11:23

1 Answers1

5

You can create BaseViewModel and define LoginModel property and inherit all View Models from BaseViewModel so you don't need to define LoginModel in every View Models you will create.

public class BaseViewModel
{
    public LoginModel LoginModel { get; set; }
}

public class ComplexViewModel : BaseViewModel
{
    public CartModel CartModel { get; set; }
}
sandip patil
  • 191
  • 4