没有带有'IEnumerable <selectlistitem>'类型的键'Value'的ViewData项目</selectlistitem>

时间:2009-10-30 23:20:24

标签: asp.net-mvc

我有以下代码:

// GET: /PlayRoundHole/Create

public ActionResult Create(int id)
{
    DB db = new DB();

    var t = db.Players.ToList();
    IList<Player> player = db.Players.ToList(); 
    IEnumerable<SelectListItem> selectList = from c in player
        select new SelectListItem
        {
            Text = c.FirstName + " " + c.LastName, 
            Value = c.PlayerID.ToString() 
        };


    this.ViewData["Players"] = new SelectList(selectList, "Value", "Text", "");

    this.ViewData["RoundID"] = id;

    return View();            
} 

//
// POST: /PlayRoundHole/Create

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
    try
    {
        DB db = new DB();

        PlayRound playRound = new PlayRound();
        playRound.PlayerID = Int64.Parse(Request.Form["Players"]);
        playRound.TenantID = 1;
        playRound.RoundID = Int64.Parse(Request.Form["RoundID"].ToString());
        playRound.Score = 0;

        var playRoundHoles = from prh in db.PlayRoundHoles.ToList()
            from hl in db.Holes.ToList()
            where prh.HoleID == hl.HoleID
            where prh.PlayRoundID == Int64.Parse(Request.Form["RoundID"].ToString())
            select new { prh.HoleID, hl.Sequence };

        foreach(var a in playRoundHoles)
        {
            PlayRoundHole playRoundHole = new PlayRoundHole();
            playRoundHole.HoleID = a.HoleID;
            playRoundHole.Stroke = Byte.Parse(Request.Form["PlayRoundHoleID_" + a.Sequence].ToString());
            playRound.PlayRoundHoles.Add(playRoundHole);
        }
        db.SubmitChanges();

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

回发时我收到上面的错误消息。

<td><%= Html.DropDownList("Value", (IEnumerable<SelectListItem>)ViewData["Players"])%></td>

不确定导致它的原因?

1 个答案:

答案 0 :(得分:3)

是否发现了错误?

如果你的代码遇到了catch,它将返回你的“Create”视图,如果在ViewData中没有指定“Player”或“Value”,则会抛出该错误,这两个都没有在你的post动作中设置。