dcpartners
dcpartners

Reputation: 5446

There is no ViewData item with the key 'Value' of type 'IEnumerable<SelectListItem>'

I have the following code:

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

I'm getting the error message above when post back.

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

Not sure why is causing it?

Upvotes: 1

Views: 999

Answers (1)

Joel
Joel

Reputation: 19358

Is an error being caught?

If your code hits the catch, it will return to your "Create" view which will throw that error if neither "Player" or "Value" is specified in the ViewData, neither of which are being set in your post action.

Upvotes: 3

Related Questions