我的代码存在问题,我正在使用MVC5附带的注册表单,我添加了一个字段“Role”作为下拉列表,在创建新用户时为用户分配角色。如下图所示
现在为了做到这一点,我修改了“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>
在Register控制器中,发布注册表单,我添加了这个
// 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
我尝试了不同的解决方案来解决它,但没有任何效果,任何人都可以提供帮助或建议吗?
答案 0 :(得分:0)
我个人会在控制器中创建选择列表并将其传递给模型,编写类似
的内容 var RolesList = new List<SelectListItem>
{
new SelectListItem { Value = string.Empty, Text = "Please select a Role..." }
};
RolesList.AddRange(roles.Select(t => new SelectListItem
{
Text = t.role,
Value = t.Id.ToString()
}));`
然后将其添加到模型中,然后在模型中使用
@Html.DropDownListFor(m => m.Role, Model.RoleList, new { @class = "form-control" })
这个方法/语法对我有用我不确定它是否是“最佳实践”但是
答案 1 :(得分:0)
在MVC5中为我编辑现有用户的解决方案
模型(部分)
public IEnumerable<string> Roles { get; set; }
查看
@Html.DropDownListFor(model => model.UserRole, new SelectList(Model.Roles, Model.UserRole), new { @class = "form-control" })
控制器(获取)
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
};
答案 2 :(得分:0)
请确保在返回视图之前将列表添加到模型中,否则会出现此错误。 示例:
cshtml:
@model DelegatePortal.ViewModels.ImpersonateVendorViewModel
@using (Html.BeginForm("ImpersonateVendor", "Admin", FormMethod.Post))
{
@Html.DropDownListFor(model => model.Id, new SelectList(Model.Vendors, "Id", "Name"), "Choose a vendor", new { @class = "form-control form-control-sm " })
}
控制器:
// GET: /Admin/ImpersonateVendor
public ActionResult ImpersonateVendor()
{
ImpersonateVendorViewModel model = new ImpersonateVendorViewModel();
var vendors = (from c in db.Vendors
select c).ToList();
model.Vendors = vendors; --> add list here
return View(model);
}
答案 3 :(得分:0)
好的,我遇到了同样的问题,除非我自己解决,否则此页面上的解决方案都不会对我有所帮助。
在发布表单时,
当我们使用
If( ModelState.IsValid())
{
//post here
}
return view (model);
实际上,我们没有在POST方法中初始化下拉列表的项目。那就是为什么抛出该nullaugumentexception的原因。我们只需要像在调用表单时一样在post方法内初始化模型中的项目列表,以便在发布过程中的模型无效时可以初始化列表,然后 将模型放入return语句中。
答案 4 :(得分:-1)
这个答案再次被编辑,现在它完美地运作
我已经提出了一个新的解决方案,我不需要创建所需的列表,我只能创建属性RoleName并使其成为必需的。
在RegisterViewModel中,我只将这些行添加到RegisterViewModel:
[Display(Name = "Roles List")]
public List<IdentityRole> RolesList { get; set; }
[Required (ErrorMessage = "Please Select the Role")]
public string RoleName { get; set; }
在视图中我按下这个下拉列表
<div class="form-group">
@Html.LabelFor(m => m.RoleName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.RoleName, new SelectList(Model.RolesList, "Name", "Name"), "Select Role", new { @class = "form-control" })
</div>
</div>
&#13;
在AccountController.CS中,Register Action是这样的:
[AllowAnonymous]
public ActionResult Register()
{
var _context = new ApplicationDbContext();
var roles = _context.Roles.ToList();
var viewModel = new RegisterViewModel
{
RolesList = roles
};
return View(viewModel);
}
以及发布表单的Register操作,我这样做了:
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)
{
await UserManager.AddToRoleAsync(user.Id, model.RoleName);
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
var _context = new ApplicationDbContext();
var roles = _context.Roles.ToList();
model.RolesList = roles;
return View(model);
}