简体   繁体   中英

Display multiple models in a single view using partial views

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.DbQuery 1[MyApp.Models.Students]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1[MyApp.Models.MyBigViewModels]'.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM