2014-03-31 36 views
0

我正在處理的應用程序涉及能夠將用戶添加到各種角色。現在我可以創建用戶和角色,並查看我的種子數據中分配給用戶的角色。但是,當我嘗試通過應用程序本身將用戶添加到角色時,這些更改實際上不會保存回數據庫。我沒有收到任何類型的錯誤頁面。這是我認爲是相關的代碼。嘗試將用戶添加到ASP.NET MVC中的角色。更改不被保存

的UserRole的方法在我的AccountController:

[Authorize(Roles = "Admin")] 
    public ActionResult UserRoles(string id) 
    { 
     var Db = new ApplicationDbContext(); 
     var user = Db.Users.First(u => u.UserName == id); 
     var model = new SelectUserRolesViewModel(user); 
     return View(model); 
    } 

    [HttpPost] 
    [Authorize(Roles = "Admin")] 
    [ValidateAntiForgeryToken] 
    public ActionResult UserRoles(SelectUserRolesViewModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      var idManager = new IdentityManager(); 
      var Db = new ApplicationDbContext(); 
      var user = Db.Users.First(u => u.UserName == model.UserName); 
      idManager.ClearUserRoles(user.Id); 
      foreach (var role in model.Roles) 
      { 
       if (role.Selected) 
       { 
        idManager.AddUserToRole(user.Id, role.RoleName); 
       } 
      } 
      return RedirectToAction("IndexUser"); 
     } 
     return View(); 
    } 

身份管理器類:

public class IdentityManager 
{ 
    public bool AddUserToRole(string userId, string roleName) 
    { 
     var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); 
     var idResult = um.AddToRole(userId, roleName); 
     return idResult.Succeeded; 
    } 

    public void ClearUserRoles(string userId) 
    { 
     var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); 
     var user = um.FindById(userId); 
     var currentRoles = new List<IdentityUserRole>(); 
     currentRoles.AddRange(user.Roles); 
     foreach (var role in currentRoles) 
     { 
      um.RemoveFromRole(userId, role.RoleId); 
     } 
    } 
} 

模型類:

public class SelectUserRolesViewModel 
{ 
    // Enable initialization with an instance of ApplicationUser: 
    public SelectUserRolesViewModel(ApplicationUser user) 
     : this() 
    { 
     this.UserName = user.UserName; 

     var Db = new ApplicationDbContext(); 

     // Add all available roles to the list of EditorViewModels: 
     var allRoles = Db.Roles; 
     foreach (var role in allRoles) 
     { 
      var rvm = new SelectRoleEditorViewModel(role); 
      this.Roles.Add(rvm); 
     } 

     // Set the Selected property to true for those roles for 
     // which the current user is a member: 
     foreach (var userRole in user.Roles) 
     { 
      var checkUserRole = this.Roles.Find(r => r.RoleID == userRole.RoleId); 
      checkUserRole.Selected = true; 
     } 
    } 

    public string UserName { get; set; } 
    public List<SelectRoleEditorViewModel> Roles { get; set; } 
} 

// Used to display a single role with a checkbox, within a list structure: 
public class SelectRoleEditorViewModel 
{ 
    public SelectRoleEditorViewModel() { } 

    public SelectRoleEditorViewModel(IdentityRole role) 
    { 
     this.RoleName = role.Name; 
     this.RoleID = role.Id; 
    } 

    public bool Selected { get; set; } 

    [Required] 
    public string RoleName { get; set; } 

    [Required] 
    public string RoleID { get; set; } 

} 

現在我知道AddUserToRole方法的工作,因爲我打電話它直接當我種子我的數據庫,它的工作原理。任何人有任何想法?

充分披露,該代碼是從以下教程採取: http://www.codeproject.com/Articles/682113/Extending-Identity-Accounts-and-Implementing-Rol

編輯: 什麼實際的網頁發生了多一點的描述。當我導航到頁面以將角色分配給所選用戶時,它會列出所有角色並預先檢查用戶已分配到的所有角色。我可以進行一些更改,然後點擊保存按鈕。但是,此時,它將返回相同的視圖,但沒有任何用戶角色信息。然後,我可以再次單擊保存並返回到用戶列表頁面。所以我猜想當頁面第一次被提交時,發生了什麼事情時,附加模型值(用戶和角色)模型狀態總是回到無效狀態,因此它繞過了UserRoles方法中的所有代碼並直接進入錯誤在最後處理返回View()行。但是,我不知道爲什麼這個模型是無效的。用戶無法輸入可能違反某種數據庫或網頁驗證的值。每個角色旁邊都有複選框,用來表示用戶將分配給哪個角色。

回答

0

在代碼中實例化了3個DbContext,看起來它們可能是嵌套的,這可能會產生問題。在你不保存更改帳戶控制器嘗試改變IdentityManager使用外部的DbContext ...

public class IdentityManager 
{ 
    private ApplicationDbContext context; 

    public IdentityManager() 
    { 
     context = new ApplicationDbContext(); // if none supplied 
    } 

    public IdentityManager (ApplicationDbContext applicationDbContext) 
    { 
     context = applicationDbContext; 
    } 

    public bool AddUserToRole(string userId, string roleName) 
    { 
     var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); 
     var idResult = um.AddToRole(userId, roleName); 
     return idResult.Succeeded; 
    } 

    public void ClearUserRoles(string userId) 
    { 
     var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); 
     var user = um.FindById(userId); 
     var currentRoles = new List<IdentityUserRole>(); 
     currentRoles.AddRange(user.Roles); 
     foreach (var role in currentRoles) 
     { 
      um.RemoveFromRole(userId, role.RoleId); 
     } 
    } 
} 

和更改調用代碼中的DbContext通過......

var Db = new ApplicationDbContext(); 
var idManager = new IdentityManager(Db); 
var user = Db.Users.First(u => u.UserName == model.UserName); 
idManager.ClearUserRoles(user.Id); 
foreach (var role in model.Roles) 
{ 
    if (role.Selected) 
    { 
     idManager.AddUserToRole(user.Id, role.RoleName); 
    } 
} 
+0

感謝您的回覆,但不幸的是,這並沒有解決問題。 – user1265215

1

數據庫
使用Db.SaveChanges();保存更改

[HttpPost] 
[Authorize(Roles = "Admin")] 
[ValidateAntiForgeryToken] 
public ActionResult UserRoles(SelectUserRolesViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     var idManager = new IdentityManager(); 
     var Db = new ApplicationDbContext(); 
     var user = Db.Users.First(u => u.UserName == model.UserName); 
     idManager.ClearUserRoles(user.Id); 
     foreach (var role in model.Roles) 
     { 
      if (role.Selected) 
      { 
       idManager.AddUserToRole(user.Id, role.RoleName); 
      } 
     } 
     Db.SaveChanges(); //for saving changes to the database 
     return RedirectToAction("IndexUser"); 
    } 
    return View(); 
} 

希望它可以幫助你,請勾選正確的答案。 :)

+0

謝謝,它沒有解決問題,但我有點尷尬,我會忘記實際上保存更改。 – user1265215

1

我希望這可以幫助遇到此問題並需要解答的人。你遇到的問題是你的model.roles返回null,所以當你嘗試添加一個新用戶時,它應該給出一個錯誤。但是,如果你檢查它不是空的,那麼它不會給出任何錯誤。另外,下次嘗試自己添加一條錯誤消息,在無法執行操作的情況下使用try catch,您會收到錯誤消息。下面試試

if (model.Roles == null) 
{ 
    model.Roles = new Role(); 
} 
    else { 
foreach (var role in model.Roles) 
     { 
      if (role.Selected) 
      { 
       idManager.AddUserToRole(user.Id, role.RoleName); 
      } 
     } 
} 
0

在你的ClearUserRoles函數中,你有um.RemoveFromRole(userId, role.RoleId);。您將RoleId放在應該是RoleName的位置。

相關問題