There is no ViewData item of type 'IEnumerable

2019-06-06 11:07发布

this is my controller action

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

in view i have populated dropdown as

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

but when i try to access the drop down value in controller i get this error "There is no ViewData item of type 'IEnumerable' that has the key 'CategoryID'."

3条回答
疯言疯语
2楼-- · 2019-06-06 11:38

Try this:

//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
}
查看更多
三岁会撩人
3楼-- · 2019-06-06 11:41

Try This:

[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();
        }

In Database Make CategoryId Allow nulls and in Model File Make it Has Nullable Ex: In Model

public int? CategoryId {get;set;}  
查看更多
4楼-- · 2019-06-06 11:47

view should be like this

@Html.DropDownListFor(item =>Model.CategoryID,ViewBag.CategoryId as SelectList,"-- Select --")
查看更多
登录 后发表回答