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.

4
  • 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 Commented Jun 26, 2013 at 5: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. Commented Jun 26, 2013 at 5:51
  • 1
    You can have base class with those model properties. Commented Jun 26, 2013 at 5:51
  • @Longball27, big thnx, I'm used this solution Commented Jun 26, 2013 at 11:23

1 Answer 1

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; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.