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 に答える