简体   繁体   English

ASP.NET MVC 4-在一个视图中提供多个模型

[英]ASP.NET MVC 4 - multiple models in one view

I'm just began new project, using ASP.NET MVC 4, and I have question. 我刚刚开始使用ASP.NET MVC 4进行新项目,我对此有疑问。

How I may use multiple models (or ViewModel-s) in one view? 如何在一个视图中使用多个模型(或ViewModel-s)? I'm searched over Internet, and standard solution is "create complex viewmodel with 2 or more properties" , eg: 我通过Internet搜索,标准解决方案是“使用2个或更多属性创建复杂的viewmodel” ,例如:

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). 但是,例如,在每个页面中,我将至少有 2个模型-LoginModel和另一个模型(取决于页面)。 So, I need to define LoginModel in each ViewModel? 因此,我需要在每个ViewModel中定义LoginModel吗?

PS: I'm using ASP.NET MVC 4, Entity Framework 5. PS:我正在使用ASP.NET MVC 4,实体框架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. 您可以创建BaseViewModel并定义LoginModel属性,并从BaseViewModel继承所有View模型,因此您无需在要创建的每个View模型中都定义LoginModel。

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

public class ComplexViewModel : BaseViewModel
{
    public CartModel CartModel { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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