我有一个搜索页面,允许用户搜索项目并向项目添加详细信息。我正在努力允许用户将相同的详细信息应用于多个项目。用户将检查他想要应用相同更改的所有项目并单击Comment
按钮。这将发送检查的项目列表List<int> ids
和单击的特定项目(在它已经存在的情况下用作模板)int id
。
从这里,用户将根据自己的意愿编辑评论并保存。行动将如何HttpPost Edit
?如果该项目尚不存在,则需要向数据库添加评论,否则,覆盖存在的内容。以下是我想出的(基本大纲)。我看到的问题是它需要为我想要应用更改的每个项目戳数据库。必须有更好的方法来做到这一点。
[HttpPost]
public ActionResult Edit(CommentVM model)
{
if (ModelState.IsValid)
{
foreach(int i in model.ids)
{
Comment comment = _db.Comments.Find(i);
if(comment == null){
//Create and add
{
else{
comment.Text = model.Text;
_db.Entry(comment).State = EntityState.Modified;
}
}
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}