ama*_*l50 6 c# asp.net asp.net-mvc-5
我的代码有问题,我正在使用MVC5附带的注册表单,我添加了一个字段"Role"作为下拉列表,在创建新用户时为用户分配角色.如下图所示

现在为了做到这一点,我修改了"RegisterViewModel"并添加了以下属性
public IdentityRole Role { get; set; }
[Required]
[Display(Name = "Roles List")]
public IEnumerable<IdentityRole> RolesList { get; set; }
Run Code Online (Sandbox Code Playgroud)
在"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);
}
Run Code Online (Sandbox Code Playgroud)
在视图"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>
Run Code Online (Sandbox Code Playgroud)
在注册控制器,发布注册表,我添加了这个
// 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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当尝试注册用户并发布表单时,我收到以下错误:
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
Run Code Online (Sandbox Code Playgroud)
我尝试了不同的解决方案来解决它,但没有任何效果,任何人都可以提供帮助或建议吗?
小智 10
您不能将<select>元素绑定到复杂对象(这是什么Role),并且当您提交表单时,它ModelState是无效的(您尝试将所选Name属性绑定RolesList到typeof IdentityRole).然后你返回视图,但没有重新填充RolesList属性,所以它null(因此错误).
视图模型不应包含数据模型,您应该查看模型
public class RegisterViewModel
{
....
[Required(ErrorMessage = "Please select a role")]
public string Role { get; set; }
public IEnumerable<SelectListItem> RoleList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并在GET方法中
var roles = _context.Roles.Select(r => r.Name);
var viewModel = new RegisterViewModel
{
RolesList = new SelectList(roles)
};
return View(viewModel);
Run Code Online (Sandbox Code Playgroud)
并在视图中
@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>
Run Code Online (Sandbox Code Playgroud)
这将解决ModelState与之相关的无效问题Role,但如果由于其他ModelState问题确实需要返回视图,则必须首先在返回视图之前重新填充集合
if (!ModelState.IsValid)
{
var roles = _context.Roles.Select(r => r.Name);
model.RolesList = new SelectList(roles);
return View(model);
}
.... // save and redirect
Run Code Online (Sandbox Code Playgroud)
就我个人而言,我会在控制器中创建选择列表并将其传递给模型,编写类似的内容
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()
}));`
Run Code Online (Sandbox Code Playgroud)
然后将其添加到您的模型中,然后您可以在模型中使用
@Html.DropDownListFor(m => m.Role, Model.RoleList, new { @class = "form-control" })
Run Code Online (Sandbox Code Playgroud)
这种方法/语法对我有用,但我不确定它是否是“最佳实践”
| 归档时间: |
|
| 查看次数: |
19143 次 |
| 最近记录: |