/ / Nie ma elementu ViewData typu „IEnumerable <SelectListItem>”, który ma klucz „CategoryID” - asp.net-mvc, razor, menu rozwijane

Nie ma elementu ViewData typu "IEnumerable <SelectListItem>", który ma klucz "CategoryID" - asp.net-mvc, brzytwa, rozwijane menu

to jest moja akcja kontrolera

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

w widoku mam wypełnione rozwijane jako

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

ale kiedy próbuję uzyskać dostęp do rozwijanej wartości w kontrolerze, pojawia się ten błąd „Nie ma elementu ViewData typu„ IEnumerable ”, który ma klucz„ CategoryID ”.”

Odpowiedzi:

3 dla odpowiedzi № 1

Spróbuj tego:

//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 dla odpowiedzi nr 2

widok powinien być taki

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

1 dla odpowiedzi nr 3

Spróbuj tego:

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

W bazie danych Make CategoryId Zezwalaj na wartości null, aw pliku modelu Make it Nullable Dawny: W modelu

public int? CategoryId {get;set;}