Guest User

Untitled

a guest
Sep 15th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. asp.mvc 4 EF ActionResult Edit with not all fields in view
  2. [HttpPost]
  3. public ActionResult Edit(User user)
  4. {
  5. if (ModelState.IsValid)
  6. {
  7. db.Entry(user).State = EntityState.Modified;
  8. db.SaveChanges();
  9. return RedirectToAction("Index");
  10. }
  11. return View(user);
  12. }
  13.  
  14. [HttpPost]
  15. public ActionResult Edit(user user)
  16. {
  17. user v = db.Users.Find(user.ID);
  18. ModelState.Remove("Pass");
  19.  
  20.  
  21. user.Password = v.Password; // assign from db
  22.  
  23. if (ModelState.IsValid)
  24. {
  25.  
  26. //db.Entry(user).State = EntityState.Modified; // this won't work as the context changed
  27. db.Entry(v).CurrentValues.SetValues(user); // we need to use this now
  28. db.SaveChanges();
  29. return RedirectToAction("Index");
  30. }
  31. return View(user);
  32. }
  33.  
  34. if (ModelState.IsValid)
  35.  
  36. if (string.IsNullOrEmpty(user.Password))
  37. {
  38. ModelState.Remove("Password");
  39. }
  40.  
  41. public class UserModel
  42. {
  43. public int Id { get; set; }
  44. public string FirstName { get; set; }
  45. public string Surname { get; set; }
  46. }
  47.  
  48. [HttpPost]
  49. public ActionResult Edit(UserModel userModel)
  50. {
  51.  
  52. if (ModelState.IsValid)
  53. {
  54. User user = db.Users.Find(userModel.Id);
  55. user.FirstName = userModel.FirstName ;
  56. user.Surname = userModel.Surname;
  57. db.SaveChanges();
  58. return RedirectToAction("Index");
  59. }
  60. return View(userModel);
  61. }
Add Comment
Please, Sign In to add comment