【问题标题】:Why does the action method DeleteConfirmed use model id rather than model object as its parameter?为什么动作方法 DeleteConfirmed 使用模型 id 而不是模型对象作为其参数?
【发布时间】:2012-09-12 17:16:09
【问题描述】:

我是 ASP.NET MVC 的新手,现在通过阅读 asp.net 中提供的教程从零开始学习。我的问题可能太简单了,但我还没有找到答案。为了快速响应,我在这里问。

编辑动作方法:

        // 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);
        }

删除动作方法:

        //
        // 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 而不是模型对象作为其参数?

【问题讨论】:

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


    【解决方案1】:

    为什么动作方法 DeleteConfirmed 使用模型 id 而不是 模型对象作为其参数?

    因为删除实体所需的只是其 id,而要编辑此实体则需要整个对象。另外我猜想调用这个 Delete 操作的视图只是在请求中发送要删除的实体的 id,所以让 delete 操作采用整个实体是没有意义的,因为它永远不会被绑定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多