Value cannot be null. Parameter name: items (in Dropdown List) ASP.NET MVC5

33,417

Solution 1

okay, i got the same problem, and none of the solution on this page helped me unless i figured it on my own.

while posting the form ,

when we use

If( ModelState.IsValid())
{
//post here


}

return view (model);

actually we are not initializing the items for dropdown list in the POST method. thats why this nullaugumentexception was thrown . we just need to initialize the list of items in the model inside the post method also as we did while calling the form, so that it can initialize the list if the model during the posting is not valid , and then put the model in return statement.

Solution 2

The solution that worked for me in MVC5 for editing an existing user

Model (part of)

public IEnumerable<string> Roles { get; set; }

View

@Html.DropDownListFor(model => model.UserRole, new SelectList(Model.Roles, Model.UserRole), new { @class = "form-control" })

Controller (Get)

 var model = new EditUserViewModel()
        {
            UserName = user.UserName,
            Email = user.Email,
            IsEnabled = user.IsEnabled,
            Id = user.Id,
            PhoneNumber = user.PhoneNumber,
            UserRole = userRoleName,

            // a list of all roles
            Roles = from r in RoleManager.Roles orderby r.Name select r.Name
        };
Share:
33,417
amal50
Author by

amal50

Updated on August 18, 2020

Comments

  • amal50
    amal50 over 3 years

    I have problem in my code. I'm using the registration form which comes with MVC5 , I added a field "Role" as a Dropdownlist to assign a role to the user while creating a new user. like in the below image: enter image description here

    Now in order to do that, I modified the "RegisterViewModel" and added the following properties:

            public IdentityRole Role { get; set; }
    
            [Required]
            [Display(Name = "Roles List")]
            public IEnumerable<IdentityRole> RolesList { get; set; }
    

    In "AccountController", I changed the Register action, that gets the registration form, to become like this:

    // GET: /Account/Register
            [AllowAnonymous]
            public ActionResult Register()
            {
    
                var _context = new ApplicationDbContext();
                var roles = _context.Roles.ToList();
    
                var viewModel = new RegisterViewModel
                {
                    RolesList = roles
                };
                return View(viewModel);
    
            }
    

    In the view "Register.cshtml" I added this Dropdownlist to load roles in the view and to post the role to the controller:

    <div class="form-group">
            @Html.LabelFor(m => m.Role.Id, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.DropDownListFor(m => m.Role, new SelectList(Model.RolesList, "Name", "Name"), "Select Role", new { @class = "form-control" })
            </div>
        </div>
    

    in the Register controller, in the the registration form post, I added this

    // POST: /Account/Register
            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> Register(RegisterViewModel model)
            {
                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser() { UserName = model.UserName , centerName = model.centerName };
                    var result = await UserManager.CreateAsync(user, model.Password);
                    if (result.Succeeded)
                    {
                        var role = new IdentityRole(model.Role.Name);
    
                        //I added this line to store the user and its roles in AspNetUserRoles table:
                        await UserManager.AddToRoleAsync(user.Id, role.Name);
    
                        await SignInAsync(user, isPersistent: false);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
    

    Now when I try to register the user and post the form, I get following error:

    Server Error in '/' Application.
    
    Value cannot be null.
    Parameter name: items
    
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
    
    Exception Details: System.ArgumentNullException: Value cannot be null.
    Parameter name: items
    
    Source Error: 
    
    
    Line 41:         @Html.LabelFor(m => m.Role.Name, new { @class = "col-md-2 control-label" })
    Line 42:         <div class="col-md-10">
    Line 43:             @Html.DropDownListFor(m => m.Role, new SelectList(Model.RolesList, "Name", "Name"), "Select Role", new { @class = "form-control" })
    Line 44:         </div>
    Line 45:     </div>
    
    Source File: c:..\TransactionsSystem\Views\Account\Register.cshtml    Line: 43 
    

    I tried different solutions to solve it, but nothing worked, can anybody please help or advise?

  • amal50
    amal50 over 7 years
    it gives me new error, (The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.Web.Mvc.SelectList‌​Item]', but this dictionary requires a model item of type 'TransactionsSystem.Models.RegisterViewModel'.)
  • amal50
    amal50 over 4 years
    You have different problem, we are initializing the list, it is the common sense
  • Ahmed Kamal
    Ahmed Kamal over 4 years
    @amal50 , you might have a different problem. but mine was this one.. i had to initialize the list in post method also..so that in case the model is not valid, then the list must be initialized again to display in the form agian