【问题标题】:There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'CategoryID'没有具有键“CategoryID”的“IEnumerable<SelectListItem>”类型的 ViewData 项
【发布时间】:2013-05-24 06:35:41
【问题描述】:

这是我的控制器操作

 public ActionResult AddNewPost(string subName)
        {
          ViewBag.CategoryID = new SelectList(from c in db.Categories where c.Status == true select c, "CategoryID", "CategoryName");
          return View();
        }

在视图中我已将下拉列表填充为

<td>
    @Html.DropDownList("CategoryID", "-- Select --")
</td>

但是当我尝试访问控制器中的下拉值时,我得到了这个错误 “没有具有键 'CategoryID' 的 'IEnumerable' 类型的 ViewData 项。”

【问题讨论】:

  • 你能写类别模型吗?
  • 嗨,你能解决这个问题吗?
  • 马杜,看我下面的帖子

标签: asp.net-mvc razor drop-down-menu


【解决方案1】:

试试这个:

//In Controller Action
public ActionResult AddNewPost(string subName)
{
    ViewBag.Cats = new SelectList(db.Categories
                             .Where(c=> c.Status)
                             .Select(c=> new {CategoryID = c.YourCatIdField, 
                                              CategoryName = c.YourCatNameField},
                             "CategoryID", "CategoryName");
    return View();
}

//In View
@Html.DropDownList("myCatId", 
                      (SelectList)(ViewData["Cats"]), "-- Select --")

//Controller
[HttpPost]
public ActionResult AddNewPost(string subName, int myCatId)
{
    //myCatId should bring the selected value here
}

【讨论】:

    【解决方案2】:

    视图应该是这样的

    @Html.DropDownListFor(item =>Model.CategoryID,ViewBag.CategoryId as SelectList,"-- Select --")
    

    【讨论】:

      【解决方案3】:

      试试这个:

      [httpGet]
      
      public ActionResult AddNewPost(string subName)
              {
                ViewBag.CategoryID = new SelectList(from c in db.Categories where c.Status == true select c, "CategoryID", "CategoryName");
                return View();
              }
      
      
      [HttpPost]
      public ActionResult AddNewPost(string subName,ur model)
              {
                model.add(model);  
                ViewBag.CategoryID = new SelectList(from c in db.Categories where c.Status == true select c, "CategoryID", "CategoryName");
                return View();
              }
      

      在数据库中使 CategoryId 允许空值并在模型文件中使其具有 Nullable 前任: 在模型中

      public int? CategoryId {get;set;}  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-26
        • 2020-06-28
        • 2020-08-20
        相关资源
        最近更新 更多