2012-04-02 66 views
5

我在這裏錯過了什麼?將mvc3中的下拉列表綁定到字典?

視圖模型:

public class ViewModel 
{ 
    public IDictionary<int, string> Entities { get; set; } 
    public int EntityId { get; set; } 
} 

控制器:

public override ActionResult Create(string id) 
    { 
     ViewModel = new ViewModel(); 

     IEnumerable<Entity> theEntities = (IEnumerable <Entity>)db.GetEntities(); 
     model.Entities= theEntities.ToDictionary(x => x.Id, x => x.Name); 

     return View(model);    
    } 

查看:

<div class="editor-field">@Html.DropDownListFor(model => model.EntityId, 
    new SelectList(Model.Entities, "Id", "Name"))</div> 
</div> 

錯誤:

DataBinding: 'System.Collections.Generic.KeyValuePair....does not contain a property with the name 'Id'

回答

14

KeyValuePair有屬性KeyValue。你最好聲明EntitiesIEnumerable<Entity>類型,那麼你的觀點將過去一樣工作:

public class ViewModel 
{ 
    public IEnumerable<Entity> Entities { get; set; } 
    public int EntityId { get; set; } 
} 

,或者,如果你真的需要使用字典<>,更改您的視圖:

<div class="editor-field"> 
    @Html.DropDownListFor(model => model.EntityId, new SelectList(Model.Entities, "Key", "Value")) 
</div> 
+0

喜,thx回覆,但我的身份證不是重疊羣。從我希望構建的列表中返回的結果選擇列表並存儲選定的ID如下:[2] =「Joes ent」,[9] =「Johns ent」...等等,所以這就是爲什麼我希望捕獲與dstabase模型中關聯的id相對應的選定id。 – Mariah 2012-04-02 21:22:57

+0

然後改變你的看法到'

@Html.DropDownListFor(model => model.EntityId, new SelectList(Model.Entities, "Key", "Value"))
' – Keith 2012-04-02 21:24:15

+0

真棒,thx !!!!!!! – Mariah 2012-04-02 21:40:14