entity framework - How to use multiple models in one view for ASP.NET MVC? -


i've read similar questions on can't seem figure out issue, specific dbcontext objects (i think). here's dummy code illustrate.

i have following code in index() action:

    public actionresult index()     {         animaldbcontext db = new animaldbcontext();          return view(db.dogs);     } 

i have following code models:

    public class dog     {         public int id { get; set; }         public string name { get; set; }         public string breed { get; set; }     }      public class animaldbcontext : dbcontext     {         public dbset<dog> dogs { get; set; }     } 

in view have following:

@model ienumerable<animalproject.models.dog>     @foreach (var d in model)     {     <h3>@d.name</h3>     <h2>@d.breed</h2>     } 

everything works great, view loop through every dog in database. however, have set of dbcontext data table want in same view. want able enumerate each item in database table well.

this want, if catch drift:

@model ienumerable<animalproject.models.dog> @model ienumerable<animalproject.models.cat>     @foreach (var d in dog)     {     <h3>@d.name</h3>     <h2>@d.breed</h2>     }     @foreach (var c in cat)     {     <h3>@c.name</h3>     <h2>@c.breed</h2>     } 

i have tried grouping classes , using partial view, apparently can't have different model in partial view, because error message:

"the model item passed dictionary of type 'system.data.entity.dbset1[animalproject.models.dog]', dictionary requires model item of type 'system.collections.generic.ienumerable1[animalproject.models.cat]'."

so, how can use multiple models in view both data want separate tables in database?

what creating custom view model class:

public animalmodel {     public ienumerable<dog> dogs { get; set; }     public ienumerable<cat> cats { get; set; } }  

fill model in index , pass view expect animalmodel instead of enumerables.

edit:

filling model:

public actionresult index() {     using (var db = new animaldbcontext())     {         var model = new animalmodel          {             dogs = db.dogs.tolist(),             cats = db.cats.tolist()         };          return view(model);     } } 

view (i have never used razor hope correct):

@model animalproject.models.animalmodel @foreach (var d in model.dogs) {   <h3>@d.name</h3>   <h2>@d.breed</h2> } @foreach (var c in model.cats) {   <h3>@c.name</h3>   <h2>@c.breed</h2> } 

Comments