因此,我有一個後臺,其中包含一個列出所有用戶的頁面和一個列出所有角色的頁面。當我編輯用戶時,我有一個包含圖片中所有角色的下拉菜單。但是我想確保每當我點擊「更新」時,用戶都通過AspNetUserRole表連接到該特定角色。我不知道如何做到這一點:/身份證都是Guid Id's。從後臺下拉菜單中分配用戶到角色
這裏是我的UserController.cs:
namespace Overnight.WWW.Areas.Backoffice.Controllers
{
[Area("Backoffice")]
public class UserController : BaseController
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
public UserController(ApplicationDbContext applicationDbContext, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager):base(applicationDbContext)
{
_userManager = userManager;
_roleManager = roleManager;
}
public async Task<IActionResult> Index(string sortParam, string searchString)
{
var model = await ApplicationDbContext.Users.OrderBy(o => o.Email).ToListAsync();
if (this.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
return PartialView("_ListPartial", model);
}
return View(model);
}
[HttpGet]
public async Task<IActionResult> Edit(Guid id)
{
if (id == null)
{
return new StatusCodeResult(400);
}
var model = await ApplicationDbContext.Users.FirstOrDefaultAsync(m => m.Id == id);
if(model == null)
{
return RedirectToAction("Index");
}
var viewModel = await ViewModel(model);
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(UserViewModel model, Guid id)
{
var alert = new Alert();
try
{
if(!ModelState.IsValid)
{
alert.Message = alert.ExceptionMessage = ApplicationDbContextMessage.INVALID;
throw new Exception();
}
var originalModel = ApplicationDbContext.Users.FirstOrDefault(m => m.Id == id);
if(originalModel == null)
{
alert.Message = alert.ExceptionMessage = ApplicationDbContextMessage.NOTEXISTS;
throw new Exception();
}
originalModel.Email = model.ApplicationUser.Email;
ApplicationDbContext.Users.Attach(originalModel);
ApplicationDbContext.Entry(originalModel).State = EntityState.Modified;
if (await ApplicationDbContext.SaveChangesAsync() == 0)
{
alert.Message = alert.ExceptionMessage = ApplicationDbContextMessage.EDITNOK;
throw new Exception();
}
alert.Message = ApplicationDbContextMessage.EDITOK;
return RedirectToAction("Index");
}
catch(Exception ex)
{
alert.Type = AlertType.Error;
alert.ExceptionMessage = ex.Message;
model = await ViewModel(model.ApplicationUser);
ModelState.AddModelError(string.Empty, alert.ExceptionMessage);
}
return View(model);
}
private async Task<UserViewModel> ViewModel(ApplicationUser user = null)
{
var roles = await ApplicationDbContext.Roles.Select(o => new SelectListItem {
Value = o.Id.ToString(),
Text = o.Name
}).ToListAsync();
var viewModel = new UserViewModel
{
ApplicationUser = (user != null)?user:new ApplicationUser(),
Roles = roles,
};
return viewModel;
}
}
}