这是AccountController.cs中的默认管理控制器
public async Task<ActionResult> Manage(ManageUserViewModel model)
{
bool hasPassword = HasPassword();
ViewBag.HasLocalPassword = hasPassword;
ViewBag.ReturnUrl = Url.Action("Manage");
if (hasPassword)
{
if (ModelState.IsValid)
{
IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
AddErrors(result);
}
}
}
else
{
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (result.Succeeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
}
else
{
AddErrors(result);
}
}
}
return View(model);
}
目前更新密码。但是,如果我想更改模型的用户名怎么办?我该如何修改这段代码?我知道一些编程,但我不知道修改这段代码?我欢迎任何帮助。感谢。
答案 0 :(得分:1)
该操作看起来特定于更改密码。我将创建一个不同的操作和视图来修改您想要更改的其他字段,如用户名,电子邮件等。表用户可以通过身份上下文使用,因此您可以按照设置Get,View和Post的典型模式:
首先制作一个你想要编辑的视图模型:
public class UserUpdateViewModel
{
[Required]
[MaxLength(50)]
public string UserName { get; set; }
[Required]
[MaxLength(50)]
public string FirstName { get; set; }
[Required]
[MaxLength(50)]
public string LastName { get; set; }
[Required]
[EmailAddress]
[MaxLength(255)]
public string Email { get; set; }
}
然后创建Get动作:
[HttpGet]
public ActionResult Edit(string id, ManageMessageId? message = null)
{
var user = _db.Users.First(u => u.UserName == id);
// move entity fields to viewmodel from constructor, automapper, etc.
var model = new UserUpdateViewModel
{
UserName = user.UserName,
FirstName = user.FirstName,
LastName = user.LastName,
Email = user.Email
};
ViewBag.MessageId = message;
return View(model);
}
然后制作一个视图,然后是帖子:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(UserUpdateViewModel userUpdateViewModel)
{
if (!ModelState.IsValid) return View(userUpdateViewModel);
var user = _db.Users.First(u => u.UserName == userUpdateViewModel.UserName);
// Mapper.Map(userUpdateViewModel, user); // move viewmodel to entity model
// instead of automapper, you can do this:
user.UserName = userUpdateViewModel.UserName;
user.FirstName = userUpdateViewModel.FirstName;
user.LastName = userUpdateViewModel.LastName;
user.Email = userUpdateViewModel.Email;
await _db.SaveChangesAsync();
return this.RedirectToAction(a => a.Index()).WithSuccess("User updated.");
}