asp.net-mvc - 将 mvc3 中的下拉列表绑定(bind)到字典?

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

我在这里想念什么?

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有属性 KeyValue .你最好声明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/

相关文章:

c# - asp.net mvc + knockout : Showing validation result from server side logic

c# - 从 MVC 中的部分 View 加载菜单

c# - 在 asp.net mvc 应用程序中对多个复选框使用属性验证

asp.net-mvc-3 - MVC3 下拉列表显示每个项目的多个属性

asp.net-mvc-3 - 范围验证在 MVC3 中无法正常工作

javascript - 如何将window.onload附加到jquery中的特定页面

c# - 如何在 MVC 模型中从 SQL Server 数据库一次检索一条记录

asp.net-mvc-3 - ASP>NET MVC 3 Controller 并发模型

c# - ASP.NET MVC 路由、TransferRequestHandler 不能在 IIS 的经典模式下工作

asp.net-mvc - 如何在 MVC3 中创建简单的路由?