Skip to content

Instantly share code, notes, and snippets.

Created February 8, 2014 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/8885857 to your computer and use it in GitHub Desktop.
Save anonymous/8885857 to your computer and use it in GitHub Desktop.
User update details
//AccountViewModel
// Return a pre-poulated instance of AppliationUser:
public ApplicationUser GetUser()
{
var user = new ApplicationUser()
{
UserName = this.UserName,
FirstName = this.FirstName,
LastName = this.LastName,
Email = this.Email,
};
return user;
}
}
public class UpdateViewModel
{
public UpdateViewModel() { }
// Allow Initialization with an instance of ApplicationUser:
public UpdateViewModel(ApplicationUser user)
{
this.UserName = user.UserName;
this.FirstName = user.FirstName;
this.LastName = user.LastName;
this.Email = user.Email;
}
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
}
}
//AccountController
//
// GET: /Account/Update
[AllowAnonymous]
public ActionResult UpdateUser(ManageMessageId? message = null)
{
var id = User.Identity.GetUserId();
var Db = new ApplicationDbContext();
var user = Db.Users.First(u => u.Id == id);
var model = new UpdateViewModel(user);
ViewBag.MessageId = message;
return View(model);
}
//
// POST: /Account/Update
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UpdateUser(UpdateViewModel model)
{
if (ModelState.IsValid)
{
var _db = new ApplicationDbContext();
var user = _db.Users.First(u => u.UserName == model.UserName);
// Update the user data:
user.FirstName = model.FirstName;
user.LastName = model.LastName;
user.Email = model.Email;
_db.Entry(user).State = System.Data.Entity.EntityState.Modified;
await _db.SaveChangesAsync();
return RedirectToAction("Index", "Home");
}
// If we got this far, something failed, redisplay form
return View(model);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment