1

这是我的控制器动作

 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>

但是当我尝试访问控制器中的下拉值时,我收到此错误“没有具有键 'CategoryID' 的 'IEnumerable' 类型的 ViewData 项。”

4

3 回答 3

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
}
于 2013-05-24T08:43:38.347 回答
2

视图应该是这样的

@Html.DropDownListFor(item =>Model.CategoryID,ViewBag.CategoryId as SelectList,"-- Select --")
于 2014-01-09T09:45:50.127 回答
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 允许空值并在模型文件中使其具有可空性 例如:在模型中

public int? CategoryId {get;set;}  
于 2013-11-13T10:44:46.997 回答