Asp.net mvc 3 是否将正确的类型从控制器传递到视图?
尝试加载视图时收到此错误消息:Asp.net mvc 3 是否将正确的类型从控制器传递到视图?,asp.net-mvc-3,Asp.net Mvc 3,尝试加载视图时收到此错误消息: The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[<>f__AnonymousType0`2[System.Int32,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic
The model item passed into the dictionary is of type
'System.Data.Entity.Infrastructure.DbQuery`1[<>f__AnonymousType0`2[System.Int32,System.String]]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[HelloWorld.Models.P]'.
以下是DBContext定义:
public DbSet<P> Ps { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//REMAPPING TABLE NAMES
modelBuilder.Entity<P>()
.ToTable("SomeTable_With_Really_LongName_tbl");
base.OnModelCreating(modelBuilder);
}
以下是观点:
@model IEnumerable<HelloWorld.Models.P>
@{
ViewBag.Title = "List P";
}
<h2>List P</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
ImportID
</th>
<th>
MicroName
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ImportID)
</td>
<td>
@Html.DisplayFor(modelItem => item.MicroName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
有什么想法吗?想想看
var model = (from p in _db.Ps
select new
{
p.ImportID,
p.MicroName
}).Take(10);
正在返回导入ID和名称,其中应返回p的枚举数
var model = _db.Ps.OrderBy(f => f.[FieldName]).Take(10);
出现此异常是因为视图需要IEnumerable类型的模型,但您正在向它传递一个匿名类型的集合模型 在控制器中,尝试以下操作:
public ActionResult ListP()
{
var model = (from p in _db.Ps
select p).Take(10);
return View(model);
}
或
迈克尔,对不起,我在“选择新”之前有一个“订购人”。你是如何设定订单的?再次感谢您的帮助。感谢Daryl给我的提示,我知道了如何在订单中输入:var model=from p in _db.Ps orderby p.CreateDate descending选择p.Take10;
var model = _db.Ps.OrderBy(f => f.[FieldName]).Take(10);
public ActionResult ListP()
{
var model = (from p in _db.Ps
select p).Take(10);
return View(model);
}
public ActionResult ListP()
{
var model = (from p in _db.Ps
select new P
{
ImportID = p.ImportID,
MicroName = p.MicroName
}).Take(10);
return View(model);
}