Full code - Strongly typed Models.Error message
Model : (file name : Class1.cs)
namespace Project
{
public class Class1
{
// attributes defined : title, date etc
}
public class Class1DBContext : DbContext
{
public DbSet<Class1> Class1Table{ get; set; }
}
public class Class2
{
// attributes defined : Name, Location etc
}
public class Class2DBContext : DbContext
{
public DbSet<Class2> Class2Table{ get; set; }
}
public class ParentView
{
public Class1 Class1{ get; set; }
public Class2 Class2{ get; set; }
}
}
In Class1Controller.cs file:
namespace Project.Controllers
{
public class Class1Controller : Controller
{
private Class1DBContext db = new Class1DBContext();
public ViewResult Index()
{
return View(db.Class1Table.ToList());
}
}
In Index.cshtml :
Index view:
@model IEnumerable<Project.Models.ParentView>
@{
ViewBag.Title = "List";
}
<div style="float:left;">
<h1 style="co开发者_JS百科lor:Black;" >List</h1>
</div>
<div>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Class1.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Class1.Description)
</td>
</tr>
}
</div>
<div>
@{Html.RenderPartial("_PartialNew");}
</div>
in partial view code (partialNew.cshtml):
@model IEnumerable<Project.Models.ParentView>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Class2.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Class2.Location)
</td>
</tr>
}
Error Message:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[Project.Models.Class1]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
1[Project.Models.ParentView]'.
Change the class to use make use of IEnumerable, e.g.:
public class ParentView
{
public IEnumerable<Class1> Class1{ get; set; }
public IEnumerable<Class2> Class2{ get; set; }
}
Remove IEnumerable so that it reads:
@model Project.Models.ParentView
Your passing a list of Class1 objects to a view that requires a list of ParentView objects. The error message is very clear here.
What is your question exactly?
Edit -
You need to return the correct type to the view, maybe something like:
public ViewResult Index()
{
var pv = new ParentView();
pv.Class1 = db.Class1Table.ToList();
pv.Class2 = db.Class2Table.ToList();
return View(pv);
}
精彩评论