Fix the “No ViewData Item” DropDownList Error in ASP.NET MVC 5
Quick fix. If the form works on GET and fails after an invalid POST, rebuild the dropdown’s options before returning the view. The browser posts the selected value. The controller must supply the available choices again.
This guide applies to ASP.NET MVC 5 on .NET Framework (System.Web.Mvc).
Identify the missing list
The message names the key MVC tried to use, often CategoryId. When a dropdown helper receives a null options list, it tries to resolve one from ViewData. Posting a numeric CategoryId supplies the current selection, while the list itself is still missing. An empty list is valid. A null list can trigger the exception.
Separate the selected value from the available options
Use a typed view model with an ID property and a separate list property. The following example uses a fixed catalog to keep the binding behavior visible. In a real application, load only options the current user is allowed to choose.
public class CategoryForm
{
[System.ComponentModel.DataAnnotations.Required]
public int? CategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
private static List<SelectListItem> CategoryOptions()
{
return new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Books" },
new SelectListItem { Value = "2", Text = "Tools" }
};
}
[HttpGet]
public ActionResult Edit()
{
return View(new CategoryForm { Categories = CategoryOptions() });
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CategoryForm input)
{
input.Categories = CategoryOptions();
if (input.CategoryId.HasValue &&
!input.Categories.Any(x => x.Value == input.CategoryId.Value.ToString()))
ModelState.AddModelError("CategoryId", "Choose an available category.");
if (!ModelState.IsValid)
return View(input);
// Save the validated category here.
return RedirectToAction("Index");
}
Render and test the form
Put these helpers inside the form for the CategoryForm model. On a failed POST, MVC normally uses the attempted value from ModelState when rendering fields. Preserve that behavior so the user can see what they submitted.
@Html.AntiForgeryToken()
@Html.DropDownListFor(m => m.CategoryId, Model.Categories, "Choose a category")
@Html.ValidationMessageFor(m => m.CategoryId)
What to verify
Submit with no selection and confirm the form reappears with its validation message and both choices. In an integration test, submit an ID outside the allowed options and confirm it is rejected, even if it is a valid integer.
Comments
Post a Comment