zoukankan      html  css  js  c++  java
  • 不存在具有键“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 常用

  • 相关阅读:
    supervise 用来监控服务,自动启动
    tee -a /var/log/jd.log
    类的构造函数与析构函数的调用顺序
    c++之带默认形参值的函数
    zoj1001-A + B Problem
    zoj1037-Gridland
    cf499A-Watching a movie
    cf478B-Random Teams 【排列组合】
    C++版修真小说
    Python_12-线程编程
  • 原文地址:https://www.cnblogs.com/senyier/p/7814686.html
Copyright © 2011-2022 走看看