I have a view that has a list of items (which can be added to dynamically via jQuery).
When I POST the viewmodel back to the controller, if the code can’t find the ID, how do I insert new items and save them to the database.
My initial code is below – the updates are saved, but the new items aren’t saved:
//
// POST: /Objective/Edit/model
[HttpPost]
public ActionResult Edit(ObjectivesEdit model)
{
if (model.Objectives != null)
{
foreach (var item in model.Objectives)
{
// find the database row
Objective objective = db.objectives.Find(item.ID);
if (objective != null)
{
// Set the database row to the posted values
objective.objective = item.objective;
objective.score = item.score;
objective.possscore = item.possscore;
}
else // database item not found, so add a new item
{
// add a new objective
// This doesn't seem to add/save a new record
Objective obj = new Objective();
obj.objective = item.objective;
obj.score = item.score;
obj.possscore = item.possscore;
}
}
// Save the changes to the database
db.SaveChanges();
}
return View(model);
}
Thanks for any help,
Mark
You don’t add the newly created objective to your context.
if you’re using EF 4.0 (i.e.
dbis of typeObjectContext), you should use thedb.AddObject(obj).Update based on your comment:
One way is to retrieve all added items after saving changes. Another way is to modify your model when creating a new objective. Changed parts are marked with *: