我在这里缺少什么?
视图模型:
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”
的属性
答案 0 :(得分:14)
KeyValuePair
包含属性Key
和Value
。您最好将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>