I'm currently working on this assignment. Everything is working fine except when I put a drop-down list from another table. I need to insert a row in my database but I'm running across an error that says
System.ArgumentNullException: 'Value cannot be null.
Parameter name: items'
I've looked for the solutions I found online but for some reason it doesn't apply to my problem.
Controller:
[HttpGet]
public ActionResult Add()
{
try
{
ViewBag.Departments = db.Departments.ToList();
return View();
}
catch (Exception genericException)
{
ViewBag.ExceptionMessage = genericException.Message;
}
return View("~/Views/Errors/Details.cshtml");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(Volunteer volunteer)
{
try
{
if (ModelState.IsValid)
{
db.Volunteers.Add(volunteer);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Department = db.Departments.ToList();
return View(volunteer);
}
catch (DbUpdateException DbException)
{
ViewBag.DbExceptionMessage = DbException.Message;
}
catch (Exception genericException)
{
ViewBag.ExceptionMessage = genericException;
}
return View("~/Views/Errors/Details.cshtml");
}
View:
@model Features.Models.Volunteer
@{
ViewBag.Title = "Add";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Add a volunteer</h2>
@using (Html.BeginForm("Add", "Volunteer"))
{
@Html.AntiForgeryToken()
<div>
<div>
@Html.LabelFor(v => v.Department)
@Html.DropDownListFor(v => v.Department, new SelectList(ViewBag.Department, "DepartmentName", "DepartmentName"), "-")
@Html.ValidationMessageFor(v => v.Department)
</div>
</div>
<input type="submit" value="Create" />
Can someone help me please? Thank you.