值不能为空。 参数名称:items(在下拉列表中)ASP.NET MVC5
我的代码有问题,我正在使用MVC5附带的注册表单,我添加了一个字段“Role”作为下拉列表,在创建新用户时为用户分配角色。 如下图所示
现在为了做到这一点,我修改了“RegisterViewModel”并添加了以下属性
public IdentityRole Role { get; set; } [Required] [Display(Name = "Roles List")] public IEnumerable RolesList { get; set; }
在“AccountController”中,我更改了注册表单的Register操作,如下所示:
// 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); }
在视图“Register.cshtml”中,我添加了此下拉列表以在视图中加载角色并将角色发布到控制器
@Html.LabelFor(m => m.Role.Id, new { @class = "col-md-2 control-label" }) @Html.DropDownListFor(m => m.Role, new SelectList(Model.RolesList, "Name", "Name"), "Select Role", new { @class = "form-control" })
在注册控制器中,发布注册表,我添加了这个
// POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task 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); } }
现在,当尝试注册用户并发布表单时,我收到以下错误:
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: Line 43: @Html.DropDownListFor(m => m.Role, new SelectList(Model.RolesList, "Name", "Name"), "Select Role", new { @class = "form-control" }) Line 44: Line 45: