Grafica Grafica - 28 days ago 11
C# Question

Why is there an error, "There is no ViewData item of type 'IEnumerable<SelectListItem>'..."

I'm creating an MVC ASP.NET form using Visual Studio 2012, C#, and Razor. After the "Submit Query" button is pressed, There is an error, "There is no ViewData item of type 'IEnumerable' that has the key 'Age'," and it's on this line in the View:


Age @Html.DropDownList("Age")


Here is the View:

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>MVC Cheese Survey</title>
</head>
<body>
<div>

@using (Html.BeginForm()) {
<div>First Name @Html.TextBox("FirstName")
Last Name @Html.TextBox("LastName")
<br />
Address @Html.TextBox("Address")
Address @Html.TextBox("Address")
City @Html.TextBox("City")
State @Html.TextBox("State")
Zip @Html.TextBox("Zip")
Phone @Html.TextBox("PhoneNumber")
Email @Html.TextBox("Email")
Age @Html.DropDownList("Age")

</div>
<input type="submit" name="submit" />
}
@ViewData["FirstName"]
</div>
</body>
</html>


Here is the Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcCheeseSurvey.Controllers
{
public class HomeController : Controller
{

public ActionResult Index()
{
List<string> AgeList = new List<string>();
AgeList.Add("0-17");
AgeList.Add("18-21");
AgeList.Add("22-25");
AgeList.Add("26-35");
AgeList.Add("36+");

ViewData["Age"] = new SelectList(AgeList);

return View();
}
[HttpPost]
public ActionResult Index(string FirstName, string LastName)
{
ViewData["FirstName"] = FirstName;
return View();
}

}
}

Answer

Both versions of the Index action need to populate the "Age" data for the ViewData, like this:

public ActionResult Index()
{   
    List<string> AgeList = new List<string>();
    AgeList.Add("0-17");
    AgeList.Add("18-21");
    AgeList.Add("22-25");
    AgeList.Add("26-35");
    AgeList.Add("36+");

    ViewData["Age"] = new SelectList(AgeList);

    return View();
}

[HttpPost]
public ActionResult Index(string FirstName, string LastName)
{
    ViewData["FirstName"] = FirstName;

    List<string> AgeList = new List<string>();
    AgeList.Add("0-17");
    AgeList.Add("18-21");
    AgeList.Add("22-25");
    AgeList.Add("26-35");
    AgeList.Add("36+");

    ViewData["Age"] = new SelectList(AgeList); 

    return View();
}
Comments