我在这里想念什么?
View 模型:
public class ViewModel
{
public IDictionary<int, string> Entities { get; set; }
public int EntityId { get; set; }
}
Controller :
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'
最佳答案
KeyValuePair
有属性 Key
和 Value
.你最好声明Entities
作为类型 IEnumerable<Entity>
,那么您的 View 将按原样工作:
public class ViewModel
{
public IEnumerable<Entity> Entities { get; set; }
public int EntityId { get; set; }
}
或者,如果您确实需要使用 Dictionary<>,请更改您的 View :
<div class="editor-field">
@Html.DropDownListFor(model => model.EntityId, new SelectList(Model.Entities, "Key", "Value"))
</div>
关于asp.net-mvc - 将 mvc3 中的下拉列表绑定(bind)到字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9983895/