Question

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.

Était-ce utile?

La solution

I would say it´s because the profile variable is not "connected" to the context. The context is not aware of the profile object. So when running context.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

Autres conseils

It looks like you aren't actually changing the data in object returned from the database. You are setting update = profile, but this just dereferences the update variable so it no longer points at the object being tracked by EF.

You need to copy all the property values from profile to update.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top