MVC4 在一个视图上为 2 个不同的相关表使用两个模型

MVC4 using two models for 2 different related tables on one view

我是 MVC 的新手。 我有 visual studio 2010 和 MVC 4.

正如我阅读的大多数文章一样,我必须创建一个模型 class,然后添加生成(创建、删除、详细信息、编辑和索引视图)的控制器。

现在假设我有两个相关表,例如:Company 和 CompanyBranches。

我可以为每一个单独创建模型、控制器和视图,但我不能合并 2 个视图(我想修改 Company 的详细信息视图,以在其上显示所有相关的 CompanyBranches。)。

我该怎么做?知道我试图将 Company Branches 模型的引用添加到 Company details 视图,但似乎在 MVC 上不允许添加两个模型。

您可以为此创建模型或视图模型:

public class ViewModel
{
   public Company MyCompany { get; set;}
   public CompanyBranches MyCompanyBranches { get; set;}

   //If you have multiple items, you can do this:
   public IList<CompanyBranches> LstCompanyBranches { get; set;}
}

那么这就是您要传递给视图的内容:

public ActionResult Create()
{
   ViewModel model = new ViewModel();
   model.MyCompany = //populate your Company details class
   model.MyCompanyBranches = //populate your CompanyBranchess class

   return View(model); //return your view with two classes on one class
}