值不能为空.参数名称:项目(在下拉列表中)ASP.NET MVC5 [英] Value cannot be null. Parameter name: items (in Dropdown List) ASP.NET MVC5
问题描述
我的代码有问题.我使用的是MVC5随附的注册表单,我添加了一个字段"Role"作为Dropdownlist,以在创建新用户时将角色分配给该用户.如下图所示:
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:
现在,为了做到这一点,我修改了"RegisterViewModel"并添加了以下属性:
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; }
在"AccountController"中,我将注册操作更改为如下形式:
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);
}
在视图"Register.cshtml"中,我添加了此下拉列表以在视图中加载角色并将角色发布到控制器:
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>
在Register控制器中的注册表单中,我添加了
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?
推荐答案
您不能将<select>
元素绑定到复杂对象(这是Role
是),并且在提交表单时,ModelState
无效(您试图将RolesList
的选定Name
属性绑定到typeof IdentityRole
).然后,您返回视图,但没有重新填充RolesList
属性,因此它的null
(因此发生错误).
You cannot bind a <select>
element to a complex object (which is what Role
is) and when you submit the form, ModelState
is invalid (your trying to bind the selected Name
property of RolesList
to typeof IdentityRole
). You then return the view, but have not repopulated the RolesList
property, so its null
(hence the error).
视图模型不应包含数据模型,而视图模型应包含
View models should not contain data models, and you view model should be
public class RegisterViewModel
{
....
[Required(ErrorMessage = "Please select a role")]
public string Role { get; set; }
public IEnumerable<SelectListItem> RoleList { get; set; }
}
以及GET方法
var roles = _context.Roles.Select(r => r.Name);
var viewModel = new RegisterViewModel
{
RolesList = new SelectList(roles)
};
return View(viewModel);
并在视图中
@Html.LabelFor(m => m.Role, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.Role, Model.RolesList, "Select Role", new { @class = "form-control" })
</div>
这将解决与Role
有关的无效ModelState
问题,但是如果由于其他ModelState
问题确实需要返回视图,则必须先重新填充集合,然后再返回视图
this will solve the invalid ModelState
issue relating to Role
, but if you do need to return the view because of other ModelState
issues, then you must first repopulate the collection before returning the view
if (!ModelState.IsValid)
{
var roles = _context.Roles.Select(r => r.Name);
model.RolesList = new SelectList(roles);
return View(model);
}
.... // save and redirect
这篇关于值不能为空.参数名称:项目(在下拉列表中)ASP.NET MVC5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!