c# - 为什么操作方法 DeleteConfirmed 使用模型 ID 而不是模型对象作为其参数?

标签 c# asp.net-mvc asp.net-mvc-4

我是 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/

相关文章:

c# - 自创建数据库以来,支持 'EmployeeDetailsContext' 上下文的模型已发生更改。

dependency-injection - ActionFilterAttribute ninject 注入(inject) - DbContext 已被释放

jquery - Kendo UI Web 和 Kendo UI ASP.NET for MVC 之间的区别

c# - 从封装类传递事件

c# - 在 C# 中将嵌入式资源作为文件复制到磁盘

asp.net - 从 Paypal 网站返回后,使用 Paypal 付款不起作用

asp.net-mvc - MVC 中 TextBoxFor 的 DisplayFormat

c# - XML 序列化和继承类型

c# - 如何通过命令行在 MSBuild 中指定 CodeAnalysisRuleset

c# - Ajax 调用在物理上不同的文件中对 Controller 较慢