0

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.

czaesar
  • 1
  • 2
  • Because in your POST method you have not set `ViewBag.Department` so its `null` (and in the view, the error is thrown at `new SelectList(ViewBag.Department, ... )` (i.e. `ModelState` is invalid and you have commented out the line with assigns it) –  Mar 14 '18 at 01:47
  • And its `ViewBag.Departments`, not `ViewBag.Department` (STOP using `ViewBag` and use view models!) –  Mar 14 '18 at 01:51
  • That was a mistake, my bad. I commented it out but I'm still having the same error. – czaesar Mar 14 '18 at 01:51
  • Read the 2nd comment :) –  Mar 14 '18 at 01:52
  • Oh, I changed it to ViewBag.Departments yesterday but for some reason it didn't work. When I tried it again just a couple of seconds ago it did work. :/ Thank you so much! – czaesar Mar 14 '18 at 01:54

0 Answers0