Aqib Mehrban Aqib Mehrban - 11 months ago 57
C# Question

How to use more than two models in MVC razor view?

I have used entity data model wizard to create an entity framework for my tables in the SQL server however I need to use more than two models in my razor view within MVC , currently I have an existing linq query in :

Controller View

var test = from a in db.tbl_users
where a == 2
select a;

return view (test.ToList());

Razor View:

@model IEnumerable <Telephone_Search.Models.tbl_users>

@foreach (var item in model)

@HTML.DisplayFor(modelItem => item.users)

However I plan to access other tables which exist in the Entity Framework which I want loop through , something like this..

@model IEnumerable <Telephone_Search.Models.'EntityFramework'>

@foreach (var item in 'entityframework')

@HTML.DisplayFor(modelItem => EntityFramework.'table'.'item')

I have tried to create a view modal however my classes are seperated within the model folder and I'm not sure how to wrap these classes into one view model?

Thank you

Answer Source

You have to create a new class, usually called a ViewModel and pass the data in that class:

public class MyViewModel
  public IEnumerable<Telephone_Search.Models.tbl_users> users;
  public IEnumerable<OtherType> otherThings;
  public string SomeOtherProp {get;set;}

In the view:

@model MyViewModel

foreach (var usr in Model.users) {...}
foreach (var ot in Model.OtherThings) {...}

In the controller:

var test = from a in db.tbl_users
       where a == 2
       select a;

var otherTypes = from x in db.tbl_otherTypes where x.Prop > 10 select x;

return this.View(new MyViewModel
  users = test,
  otherThings = otherTypes,
  SomeOtherProp = "stackoverflow answer"