我是 ASP.NET MVC 的新手,现在通过阅读 asp.net 中给出的教程从零开始学习。我的问题可能太简单了,但我还没有找到答案。为了快速回复,我在这里问。
编辑 Action 方法:
// GET: /Movie/Edit/5
public ActionResult Edit(int id = 0)
{
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
return View(movie);
}
//
// POST: /Movie/Edit/5
[HttpPost]
public ActionResult Edit(Movie movie)
{
if (ModelState.IsValid)
{
db.Entry(movie).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}
删除 Action 方法:
//
// GET: /Movie/Delete/5
public ActionResult Delete(int id = 0)
{
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
return View(movie);
}
//
// POST: /Movie/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Movie movie = db.Movies.Find(id);
db.Movies.Remove(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
让我们比较一下用于更新和删除的 HTTP POST。我很好奇:
为什么操作方法 DeleteConfirmed 使用模型 id 而不是模型对象作为其参数?
最佳答案
Why does the action method DeleteConfirmed use model id rather than model object as its parameter?
因为要删除一个实体,您只需要它的 ID,而要编辑该实体,您需要整个对象。此外,我猜想调用此 Delete 操作的 View 仅在请求中发送要删除的实体的 ID,因此删除操作采用整个实体是没有意义的,因为它永远不会被绑定(bind)。
关于c# - 为什么操作方法 DeleteConfirmed 使用模型 ID 而不是模型对象作为其参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12384793/