首先创建视图模型
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Shop.ViewModel { public class CreateEditRoleViewModel { [Required(ErrorMessage = "角色名不能为空")] [DisplayName("角色名")] public string Name { get; set; } } }
增加角色方法
// GET: RoleController/Create public ActionResult Create() { return View(); } // POST: RoleController/Create [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(CreateEditRoleViewModel input) { if (!ModelState.IsValid) { return View(input); } var role = new IdentityRole { Name = input.Name }; var result = await _roleManager.CreateAsync(role); if (result.Succeeded) { return RedirectToAction("Index"); } foreach (var item in result.Errors) { ModelState.AddModelError(string.Empty, item.Description); } return View(input); }
创建角色视图
@model Shop.ViewModel.CreateEditRoleViewModel @{ ViewData["Title"] = "Create"; } <h1>Create</h1> <h4>创建角色</h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Create" method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
显示效果及验证报错效果