简体   繁体   中英

ASP.NET MVC 4 - multiple models in one view

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" , eg:

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?

PS: I'm using ASP.NET MVC 4, Entity Framework 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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM