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'."
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
}
view should be like this
@Html.DropDownListFor(item =>Model.CategoryID,ViewBag.CategoryId as SelectList,"-- Select --")
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;}