2015-05-09 83 views
-2
[HttpGet] 
public ActionResult Edit(int id) 
{ 
    var userToEdit = _db.AuthLogin.Where(user => user.Id == id).SingleOrDefault(); 
    if (userToEdit == null) 
     return HttpNotFound(); 


    return View(new EditUser() 
    { 
     Email = userToEdit.Email, 
     UserName = userToEdit.UserName, 
     Password = userToEdit.Password, 
     Roles = _db.Roles.Select(role => new RoleCheckBox 
     { 
      Id = role.Id, 
      IsChecked = userToEdit.Roles.Contains(role), 
      Name = role.Name 
     }).ToList() 
    }); 
} 

回答

0

我不知道你的Role類是如何定義的,但你可以嘗試這樣的事:

List<int> userRoleIds = userToEdit.Roles.Select(r => r.Id).ToList(); 
    EditUser model = new EditUser() 
    { 
     Email = userToEdit.Email, 
     UserName = userToEdit.UserName, 
     Password = userToEdit.Password, 
     Roles = _db.Roles.Select(role => new RoleCheckBox 
     { 
      Id = role.Id, 
      IsChecked = userRoleIds.Contains(role.Id), 
      Name = role.Name 
     }).ToList() 
    }); 
    return View(model); 

或更改

_db.Roles.Select(...) 

_db.Roles.ToList().Select(...) 
相關問題