There is no ViewData item of type 'IEnumerable

2019-06-06 11:35发布

问题:

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'."

回答1:

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
}


回答2:

view should be like this

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


回答3:

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;}