1

I need to is display data from a two tables(Student and Grade) in a single view index.cshtml.

I have two partial views _StudentPartial & _GradePartial both strongly typed. I googled around and everyone says that I parent model should be used. So I created a parent model called MyViewModels below but I can't seem to get this to work. What's the correct way to do this?

My Model:

public class MyBigViewModels{
      public IEnumerable<Users.Models.Student> Student      { get; set; }
      public IEnumerable<Users.Models.Grade>   Grade       { get; set; }
}

My View():

@model MyApp.Models.MyBigViewModels

// render content for Student 
@foreach (var item in Model)
{
  @Html.Partial("_StudentPartial", item)
}

// Render content for Grades
@foreach (var item in Model)
{
  @Html.Partial("_GradePartial", item)
}

My Partial Views

// _StudentPartial 
@model IEnumerable<MyApp.Models.Student>

@foreach (var item in Model) {
 @Html.DisplayFor(modelItem => item.name)
}


 // _GradePartial
@model IEnumerable<MyApp.Models.Grade>

@foreach (var item in Model) {
 @Html.DisplayFor(modelItem => item.letterGrade)
}

Server Error in '/' Application

The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery1[MyApp.Models.Students]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[MyApp.Models.MyBigViewModels]'.

ceci
  • 429
  • 1
  • 7
  • 22

1 Answers1

2

in your outer view:

@foreach (var item in Model)

doesn't make sense. Your model is not enumerable. You want :

@foreach (var item in Model.Students)
{
   @Html.Partial("_StudentPartial", item)
}

// Render content for Grades
@foreach (var item in Model.Grades)
{
   @Html.Partial("_GradePartial", item)
} 

and your partials would just take a single item:

@model MyApp.Models.Student

@Html.DisplayFor(modelItem => item.name)

either that, or don't loop in your main page, and send the enumerables into your partials to loop. Essentially you have 2 foreach's when you only need one.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112