这是我的控制器动作
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>
但是当我尝试访问控制器中的下拉值时,我收到此错误 “没有类型'IEnumerable'的ViewData项具有密钥'CategoryID'。”
答案 0 :(得分:3)
试试这个:
//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
}
答案 1 :(得分:2)
视图应该是这样的
@Html.DropDownListFor(item =>Model.CategoryID,ViewBag.CategoryId as SelectList,"-- Select --")
答案 2 :(得分:1)
试试这个:
[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;}