2012-06-08 100 views
0

得到嘗試加載鑑於此錯誤消息:將正確的類型從Controller傳遞給View?

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]'. 

難道是從沒有從控制器傳遞正確的類型有何看法?

這裏的模型:

public class P 
{ 
    [Key] 
    public virtual int ImportID { set; get; } 
    public virtual string MicroName { set; get; } 
} 

這裏的的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); 
} 

這裏的控制器動作:

public ActionResult ListP() 
{ 

var model = (from p in _db.Ps 
select new 
{ 
p.ImportID, 
p.MicroName 
}).Take(10); 

return View(model); 
} 

這裏的觀點:

@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> 

有什麼建議嗎?

回答

1

認爲

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); 
+0

確定;當我回去工作時我會嘗試。謝謝! – scv

+0

邁克爾, 對不起,我有一個'訂購'右選擇新之前。 你如何去設置訂單? 再次感謝您的幫助。 – scv

0

您收到此異常,因爲視圖期待類型的模型IEnumerable<HelloWorld.Models.P>,但是您傳遞的是一個匿名類型集合的模型。

在控制器試試這個:

public ActionResult ListP() 
{ 
    var model = (from p in _db.Ps 
       select p).Take(10); 

    return View(model); 
} 

OR

public ActionResult ListP() 
{ 
    var model = (from p in _db.Ps 
       select new P 
       { 
        ImportID = p.ImportID, 
        MicroName = p.MicroName 
       }).Take(10); 

    return View(model); 
} 
+0

感謝達里爾爲尖端 我想出如何放在以便通過: VAR模型=(從_db.Ps p 的OrderBy p.CreateDate降序 選擇P)。取(10); – scv

+0

太棒了! – scv

相關問題