使用(显示)我当前视图中另一个模型的数据

0 asp.net asp.net-mvc razor

没有代码可显示。我只是想明白一些事情。我已经做了一些 MVC 代码(我有一个模型,我要求 Visual Studio 创建控制器和视图)。每个视图仅与“一个模型”关联。因此,使用 Razor,我可以显示该模型的数据。我玩了我的代码,到目前为止我已经理解了。

但是......在同样的观点上,我们如何与另一个模型合作?

对我来说,模型只是一个具有属性等的类。我的数据库为每个模型都有一个等效的“数据表”。我可以用实体框架操纵它......没问题。但是,我需要在同一视图中使用来自不同模型(不同表)的数据,而 Visual Studio 不允许我在视图中使用另一个模型。

策略是什么?(或者也许我不明白一些事情......)

谢谢。

Adr*_*ris 6

策略是构建一个视图模型,一个为了显示而构建的模型,并表示您需要使用的数据。

例子 :

您有这些类,这些类代表您的数据库:

public class FootballTeam{
     public string Name{get;set;}
     public string Logo{get;set;}
}

public class FootballGame{
     public Datetime Date {get;set;}
     public string Competition {get;set;}
}

public class Referee{
     public string Name{get;set;}
     public int Experience {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

要显示有关比赛的信息,您可以为此类创建一个视图模型,必要时该类可以引用您的业务模型的某些类:

public class GameViewModel{
     [DisplayName("Home team")]
     public FootballTeam HomeTeam{get;set;}

     [DisplayName("Referee")]
     public Referee Referee{get;set;}

     [DisplayName("Visitor team")]
     public FootballTeam VisitorTeam {get;set;}

     [DisplayName("Comments")]
     public List<string> RedactionComments{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

并创建一个将使用此 GameViewModel 的视图。一般来说,当您创建一个新的 MVC 项目时,您的表示层中会有一个名为“ViewModels”的文件夹,其中包含一些像这样的类。

此方法允许将业务模型与表示模型分开,这是两个完全不同的事物。

这里有很好的答案:What is ViewModel in MVC?