Created
February 8, 2014 15:59
-
-
Save anonymous/8885857 to your computer and use it in GitHub Desktop.
User update details
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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