【发布时间】:2018-08-22 10:32:21
【问题描述】:
我的代码有问题。我正在使用 MVC5 附带的注册表单,我添加了一个字段“角色”作为下拉列表,以便在创建新用户时为用户分配角色。如下图所示:
现在为了做到这一点,我修改了“RegisterViewModel”并添加了以下属性:
public IdentityRole Role { get; set; }
[Required]
[Display(Name = "Roles List")]
public IEnumerable<IdentityRole> RolesList { get; set; }
在“AccountController”中,我将获取注册表单的注册操作更改为如下所示:
// 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”视图中,我添加了这个下拉列表以在视图中加载角色并将角色发布到控制器:
<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>
在注册控制器中,在注册表单中,我添加了这个
// 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);
}
}
现在,当我尝试注册用户并发布表单时,出现以下错误:
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
我尝试了不同的解决方案来解决它,但没有任何效果,有人可以帮忙或建议吗?
【问题讨论】:
-
确保 var roles = _context.Roles.ToList();正在返回所有角色的值。
-
不,它不会复制任何东西,这是我的代码中的一个特定问题,而不是关于 NullReferenceException 含义的一般问题,我该如何解决?
标签: c# asp.net asp.net-mvc-5