将mvc3中的下拉列表绑定到字典?

时间:2012-04-02 21:12:44

标签: asp.net-mvc asp.net-mvc-3

我在这里缺少什么?

视图模型:

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 ....没有   包含名为“Id”

的属性

1 个答案:

答案 0 :(得分:14)

KeyValuePair包含属性KeyValue。您最好将Entities声明为类型IEnumerable<Entity>,然后您的视图将按原样运行:

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

或者,如果您确实需要使用词典&lt;&gt;,请更改您的观点:

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