不存在具有键“xxxId”的“IEnumerable<SelectListItem>”类型的 ViewData 项

项目中的某个页面,在访问时出现以下错误:

不存在具有键“xxxId”的“IEnumerable<SelectListItem>”类型的 ViewData 项

具体的场景说明如下:

  一个编辑页,其中某下拉控件绑定值为来自model对象中的一个List<SelectListItem>集合属性。具体看下面:

     Ⅰ、前端视图页面的代码

  @Html.DropDownListFor(p => p.SubitemTypeId,(Model.SubitemTypeList as List<SelectListItem>),
                        new { @class = "form-control" })

     Ⅱ、后端控制器中返回视图的action

        public ActionResult EditSubitem(long? id)
        {
            var entObj = new SubitemModel();//初始化基础数据

            if (id!=null&&id!=0)
            {
                entObj = _SubitemAppService.GetSubitem(id.Value);
            }
            entObj.SubitemTypeList = _SubitemTypeAppService.SubitemTypeList();//返回List<SelectListItem>的集合

            return View(entObj);
        }

1)当_SubitemTypeAppService.SubitemTypeList()返回集合不为空时,访问页面下拉控件不会报错;

2)当_SubitemTypeAppService.SubitemTypeList()返回集合为空时,访问页面时,下拉控件会报文章开头的错

原因:当返回为空值时,则Model.SubitemTypeList为null值,当然不能转化为 List<SelectListItem>下拉项。

处理方式为修改页面绑定的值的方式,当为null时增加一个为空的默认项

@Html.DropDownListFor(p => p.SubitemTypeId, 
Model.SubitemTypeList==null?new List<SelectListItem> { new SelectListItem { Text="无选项",Value=""} } : (Model.SubitemTypeList as List<SelectListItem>), new { @class = "form-control" })

在网上查找时,发现还有一种情况也会出现以上报错:http://bbs.csdn.net/topics/380095463

ASP.NET MVC 3 常用

 

posted on 2017-11-10 14:51  儿时精神  阅读(5496)  评论(0编辑  收藏  举报

导航