As an option you can create a new view model for role creation. This is similar to what has been done for users in the default MVC project template when you enable individual users authentication. If you take a look at AccountViewModels.cs
, you see a couple of view models.
For example, you can create the following class:
public class ApplicationRoleCreateModel
{
[Required]
public string Name { get; set; }
[Required]
[Display(Name = "Application Id")]
public string ApplicationId { get; set; }
}
Supposing you have created ApplicationRole
class including custom properties as described here, then can create the following role controller class:
[Authorize]
public class RoleController : Controller
{
private ApplicationRoleManager _roleManager;
public RoleController() { }
public RoleController(ApplicationRoleManager roleManager)
{
RoleManager = roleManager;
}
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ??
HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set { _roleManager = value; }
}
public ActionResult Index()
{
var model = RoleManager.Roles.ToList();
return View(model);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Create(ApplicationRoleCreateModel model)
{
if (ModelState.IsValid)
{
var result = await RoleManager.CreateAsync(new ApplicationRole()
{
Name = model.Name,
ApplicationId = model.ApplicationId
});
if (result.Succeeded)
return RedirectToAction("Index");
else
foreach (var error in result.Errors)
ModelState.AddModelError("", error);
}
return View();
}
}