niico
niico

Reputation: 12729

ASP.NET MVC 4 - how to use a viewmodel when editing & persisting data

mvc 4 using sql server 2008, code first, ef5

I have a ViewModel associated with a view.

As a starting point I'm modifying the scaffolding created by VS.

I can populate the form fine.

When the user clicks save - this is the code in the scaffolding:

 [HttpPost]
 public ActionResult Edit(Place place)
 {
 if (ModelState.IsValid)
    {
       db.Entry(place).State = EntityState.Modified;
       db.SaveChanges();
       return RedirectToAction("Index");
    }
 return View(place);

Place is a model. I need to pass a viewmodel (including place) back to this.

How do I persist the viewmodel in the database using EF? Do I have to split it into models first?

When I try that I get this error:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

When I debug it also seems the PlaceID (from model) is missing from the model that's passed back to the controller httpPost Edit controller - maybe that's the source of the error?

Are there any examples of best practice online for this - I can't find anything.

Thanks.

Upvotes: 2

Views: 3227

Answers (2)

niico
niico

Reputation: 12729

This was missing in the View:

@Html.HiddenFor(model => model.place.PlaceID)

This keeps tabs on the ID of the model

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

How do I persist the viewmodel in the database using EF?

You do not persist view models in a database. They role is not to be persisted. View models are used to define the logic used by your view. It is inside your controller action that you could map the view model back to your domain model that will be persisted using the data access technology of your choice. You could use AutoMapper to map between your view models and domain models.

When I debug it also seems the PlaceID (from model) is missing from the model that's passed back to the controller httpPost Edit controller - maybe that's the source of the error?

Yes, that's the possible reason. If you want to update some record in the database EF need to know which is this record using the ID.

Upvotes: 6

Related Questions