I wrote my code in ASP.NET MVC 4. I Create a Edit form using MVC edit template and this is my POST code to save edited data.
[AcceptVerbs(HttpVerbs.Post)] [Authorize(Roles = "User")] public ActionResult Register(Models.UserBasicProfile profile) { if (ModelState.IsValid) { using (Models.SocialServicesDataContainer context = new Models.SocialServicesDataContainer()) { Models.UserBasicProfile update = context.UserBasicProfiles .SingleOrDefault(c => c.Id == profile.Id); if (update.Id > 0) { profile.RegisterDate = update.RegisterDate; update = profile; context.SaveChanges(); return RedirectToRoute("User_ShowProfile_Alter", new {username = User.Identity.Name }); } else { return View(profile); } } }
This code run correctly and there is no error. But when redirect to user profile occurred, modified fields are still have the previous value.
What should I do ?
Thanks in advance.
I would say it´s because the
profilevariable is not “connected” to the context. The context is not aware of the profile object. So when runningcontext.SaveChanges()the changes in the profile variable goes unnoticed.You need to update the
update object with the values from profile. Or perhaps attach the profile object to the context.Check this post on how to attach to the context prior saving Entity Framework 4 – AddObject vs Attach