2012-04-02 30 views
5

Tôi đang thiếu gì ở đây?Ràng buộc danh sách thả xuống bằng mvc3 vào từ điển?

ViewModel:

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

Bộ điều khiển:

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);    
    } 

Xem:

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

Lỗi:

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

Trả lời

14

KeyValuePair có các thuộc tính KeyValue. Bạn đang khấm khá hơn tuyên bố Entities as type IEnumerable<Entity>, sau đó xem bạn sẽ làm việc như-là:

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

OR, nếu bạn thực sự cần phải sử dụng một từ điển <>, thay đổi quan điểm của mình:

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

hi , thx để trả lời nhưng id của tôi không phải là contig. Kết quả từ danh sách mà tôi muốn xây dựng danh sách lựa chọn và lưu trữ id được chọn giống như: [2] = "Joes ent", [9] = "Johns ent" ... vv, ... vì vậy đó là lý do tôi muốn nắm bắt id đã chọn tương ứng với id được liên kết trong mô hình dstabase. – Mariah

+0

Sau đó, thay đổi chế độ xem thành '

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

+0

Tuyệt vời, thx !!!!!!! – Mariah

Các vấn đề liên quan