1
美好的一天,如何更新ASP.NET身份中的UserManager?
我在asp.net Identity 2.0 MVC5中創建並分配了一個帶有密碼的用戶(並且幾乎不是新的)並且在登錄時;我指示用戶創建(更新)他/她的帳戶。
一切順利,但是當用戶提交更新時,它並不反映在數據庫中。它似乎錯過了我的代碼中的正確邏輯。這是我的ViewModel和控制器。
拜託,我需要你的幫助。
public class EditUserViewModel
{
[Key]
public string Id { get; set; }
[Required]
[Display(Name = "Surname")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Username")]
public string Username { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Display(Name = "Gender")]
public string Gender { get; set; }
[Required]
[Display(Name = "Mobile Phone")]
public string PhoneNumber { get; set; }
//[Required]
[Display(Name = "Birthday - yyyy/mm/dd")]
public DateTime DateOfBirth { get; set; }
//public DateTime PostedDate { get; set; }
}
Controller:
[HttpGet, ActionName("profile")]
public ActionResult Edit()
{
return View();
}
[HttpPost, ActionName("profile")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(EditUserViewModel editUser)
{
if (ModelState.IsValid && TempData["Username"] != null)
{
var user = await UserManager.FindByNameAsync(editUser.Username);
if (user == null)
{
return HttpNotFound(); //change error later
}
user.FirstName = editUser.FirstName;
user.LastName = editUser.LastName;
user.UserName = editUser.Email;
user.Email = editUser.Email;
user.PasswordHash = editUser.Password;
var userUpdated = await UserManager.UpdateAsync(user);
if (!userUpdated.Succeeded)
{
ModelState.AddModelError("", userUpdated.Errors.First());
return View();
}
return RedirectToAction("index", "pages");
}
ModelState.AddModelError("", "Something failed!!!");
return View();
}
感謝Bobby Caldwell。我錯過了密碼。然而,我調試狀態時得到的錯誤var user = await UserManager.FindByNameAsync(editUser.Username)爲空。 –
啊我看到了,所以用戶可能還沒有創建。您應該創建一個新用戶,而不是拋出一個錯誤?如果找不到,我會更新我的答案以反映添加新用戶。 –
我想要實現的目標是在用戶登錄到他們可以更新他們的個人資料(名字,姓氏,用戶名,密碼等)的網頁後面,直接與他們使用的用戶名和密碼對照。 –