pbristow
pbristow

Reputation: 2175

ASP.NET MVC3 Model Binding on Edit

I'm working on my 5th or so ASP.NET MVC webapp in the past few years, and I still haven't seen a good way to take the data submitted in an Edit/Update form and save it to the database efficiently when using an ORM like Linq to SQL or the Entity Framework.

Just to be clear, the problem is with the Create action you can take the object as a parameter:

public ActionResult Create(QuestionGroup newGroup)

With an Edit action, the object must be linked to the ORM and updated, rather than created from scratch like the ModelBinder will do.

I have always solved this problem one of two ways: either I will manually update each property on the object (one line of code per property) or I will write a method that uses reflection to find every property to update it and copies the value over.

I feel certain that, by now in version 3 of MVC, there is a blessed way to do this better, but I cannot find it! What's the secret to do this more simply and gracefully??

Upvotes: 2

Views: 2007

Answers (2)

pbristow
pbristow

Reputation: 2175

I've discovered that you can also do the following with the Entity Framework. It has pros and cons vs the other option, but it should work just as well as the previous answer:

[HttpPost]
public ActionResult Edit(QuestionGroup updatedGroup)
{
    try
    {
        context.QuestionGroups.Attach(updatedGroup);
        context.ObjectStateManager.ChangeObjectState(updatedGroup, System.Data.EntityState.Modified);

        ValidateModel(updatedGroup);

        if (this.ModelState.IsValid)
        {
            context.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch
    {
    }

    return View();
}

Upvotes: 2

pbristow
pbristow

Reputation: 2175

Well this is embarrassing... there is a method Controller.UpdateModel with several overloads that will do the trick. I searched the internet hi and low, only to accidentally find the answer with IntelliSense right after posting the question.

Upvotes: 2

Related Questions