加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – Controller如何知道MVC中DeleteConfirmed的Id?

发布时间:2020-12-16 09:53:32 所属栏目:asp.Net 来源:网络整理
导读:嗨,有人可以解释一下Visual Studio生成的默认删除方法是如何工作的.我很困惑,因为当你发布DeleteConfirmed时,模型Id被传递回控制器.但是在View中,即使在隐藏字段中也没有生成Id字段,那么为什么Id不会丢失/重置在Post上? Controller如何知道Id? 视图 @{ Vie
嗨,有人可以解释一下Visual Studio生成的默认删除方法是如何工作的.我很困惑,因为当你发布DeleteConfirmed时,模型Id被传递回控制器.但是在View中,即使在隐藏字段中也没有生成Id字段,那么为什么Id不会丢失/重置在Post上? Controller如何知道Id?

视图

@{
        ViewBag.Title = "Delete";
    }

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<fieldset>
    <legend>SellersQuery</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Name)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Name)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Manufacturer)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Manufacturer)
    </div>
</fieldset>
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    <p>
        <input type="submit" value="Delete" /> |
        @Html.ActionLink("Back to List","Index")
    </p>
}

调节器

public ActionResult Delete(int id = 0)
        {
            SellersQuery sellersquery = db.SellerQuerySet.Find(id);
            if (sellersquery == null)
            {
                return HttpNotFound();
            }
            return View(sellersquery);
        }

        [HttpPost,ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            SellersQuery sellersquery = db.SellerQuerySet.Find(id);
            db.SellerQuerySet.Remove(sellersquery);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

解决方法

您的GET删除URL可能类似于/ Controller / Action / Id. 因此,即使表单中没有ID字段,在提交表单时,URL中的ID也会映射到method参数中的ID.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读