-1

I'm trying to get the selected value of a dropdown from the Edit view to the controller. I keep getting the same error "{"Value cannot be null.\r\nParameter name: items"}"

Here is my view:

<div class="form-group">
    @Html.LabelFor(model => model.adminID, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.adminID, new SelectList(ViewBag.Admins, "Value", "Text"), htmlAttributes: new { @class = "form-control", @name = "admin" })
        @Html.ValidationMessageFor(model => model.adminID, "", new { @class = "text-danger" })
    </div>
</div>

I created the SelectList in the get action.

var admins = from a in db.members
                     select new { name = a.student.Fname + " " + a.student.Sname, id = a.StudentID };

ViewBag.Admins = admins.Select(a => new SelectListItem
{
    Text = a.name,
    Value = a.id
}).ToList();

And here is the controller. I used adminID, the name of the property to try bind it but it returns the error when I post the page.

public async Task<ActionResult> Edit([Bind(Include = "ClubId,ClubName,CreationDate,adminID")] Club club)
{
    if (ModelState.IsValid)
    {
        db.Entry(club).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(club);
}

The Error being returned is

"{"Value cannot be null.\r\nParameter name: items"}"

Any ideas why the adminID won't save/bind? enter image description here

Route Config

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Clubs", action = "Index", id = UrlParameter.Optional }
        );
    }
}
Marc
  • 3,905
  • 4
  • 21
  • 37
Ryan Spain
  • 61
  • 7

2 Answers2

0

The name of the DropdownListFor must have the same name as property of the object, otherwise use FormCollection, get value from form instance and assign to the property

Shaahin
  • 1,195
  • 3
  • 14
  • 22
0

I think that since you're naming the drop down list as "admin", when it posts back, MVC doesn't know where to stick the value because you don't have a value in the post method's parameters named admin.

If you remove the @name, it should work.

@Html.DropDownListFor(model => model.adminID, new SelectList(ViewBag.Admins, "Value", "Text"), htmlAttributes: new { @class = "form-control" })

Another thing, You're creating a new select list in the controller then passing it into the viewdata, so you have a select list in the view data at this point. Then in the view, you're declaring another select list so you have a SelectList of SelectLists with one element.

Jesse Moreland
  • 441
  • 6
  • 17