加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:41:44 所属栏目:asp.Net 来源:网络整理
导读:我在这里错过了什么? 视图模型: public class ViewModel{ public IDictionaryint,string Entities { get; set; } public int EntityId { get; set; }} 控制器: public override ActionResult Create(string id) { ViewModel = new ViewModel(); IEnumerab
我在这里错过了什么?

视图模型:

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….does not
contain a property with the name ‘Id’

解决方法

KeyValuePair具有Key和Value属性.您最好将实体声明为类型IEnumerable< Entity>,然后您的视图将按原样运行:

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

或者,如果您确实需要使用词典<>,请更改您的视图:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读