我有一个包含项目列表的视图(可以通过 jQuery 动态添加)。
当我将视图模型 POST 回控制器时,如果代码找不到 ID,我该如何插入新项目并将它们保存到数据库中。
我的初始代码如下 - 更新已保存,但新项目未保存:
//
// 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);
}
谢谢你的帮助,
标记