2012-04-02 13 views
5

私はここで何が欠けていますか?mvc3のドロップダウンリストを辞書にバインドしますか?

のViewModel:

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です。あなたがタイプIEnumerable<Entity>としてEntitiesを宣言するほうが良いでしょう、そして、あなたのビューがあるとして、働くだろう:

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

こんにちは:あなたは本当に辞書<>を使用する必要がある場合、

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

をOR、あなたのビューを変更します、返信のためのthxしかし私のidはcontigではない。選択リストを作成して選択したIDを保存するリストからの結果は、次のようになります。[2] = "Joes ent"、[9] = "Johns ent" ...など。 dstabaseモデルの関連IDに対応する選択されたIDを取得します。 – Mariah

+0

次に、ビューを「

@Html.DropDownListFor(model => model.EntityId, new SelectList(Model.Entities, "Key", "Value"))
」 – Keith

+0

「Awesome、thx !!!!!!!」に変更します。 – Mariah

関連する問題