1

I'm very new to MVC. I have visual studio 2010 and MVC 4.

as most articles I read, I have to create a model class, and then add Controller which generate (create, delete, details, Edit and Index views).

now suppose that I have two related tables, like: Company and CompanyBranches.

I can create model, controller and views for each one individually but I can't combine 2 views (I want to modify the details view of Company, to display all related CompanyBranches on it.).

How can I do this? Knowing that I tried to add a reference for Company Branches model to Company details view, but it looks like adding two models is not allowed on MVC.

user6218508
  • 200
  • 1
  • 9

1 Answers1

2

You can create a Model or ViewModel for this:

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;}
}

Then this is what you will pass to your view:

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
}
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
  • When I write @model IEnumerable on the view, the following error is displayed when loading the page: The model item passed into the dictionary is of type 'AttendanceProject.Models.CompanyRelatedBranches', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[AttendanceProject.Models.CompanyRelatedBranches]'. – user6218508 Sep 12 '17 at 06:20
  • It should be @model AttendanceProject.Models.ViewModel Then in order to access the properties of your CompanyRelatedBranches, you would call them like this: Model.CompanyRelate‌​dBranches.Property – Willy David Jr Sep 12 '17 at 06:24
  • I have already tried that, but then VS mark the following loop as error: @foreach (var item in Model) { @Html.DisplayFor(modelItem => item.companyBranches.branchName); } – user6218508 Sep 12 '17 at 06:31
  • I updated my code, you are doing it wrong since you are ienumerating on list of branches. Check my updated code where I put a List on my View Model. @user6218508 – Willy David Jr Sep 12 '17 at 06:35
  • Finally it's worked! Thank you very much. – user6218508 Sep 12 '17 at 07:19