【问题标题】:Direct delete link from index view instead of going to delete page直接从索引视图中删除链接,而不是去删除页面
【发布时间】:2018-07-22 20:48:02
【问题描述】:

我正在尝试创建一个链接,该链接将删除其中一条记录,而无需转到删除页面。

我的删除部分控制器:

 // GET: Cars/Delete/5
    public async Task<ActionResult> Delete(Guid? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Car car = await db.Cars.FirstOrDefaultAsync();
        if (car == null)
        {
            return HttpNotFound();
        }
        return View(car);
    }

    // POST: Cars/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> DeleteConfirmed(Guid id)
    {
        Car car = await db.Cars.FindAsync(id);
        db.Cars.Remove(car);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

在视图中,我试图有一个链接直接删除它:

<a href="@Url.Action("DeleteConfirmed", "Cars", new { id=item.Id })" class="btn btn-danger btn-sm" onclick = "return confirm('Are sure wants to delete?');">
    <i class="fa fa-times" aria-hidden="true"></i>
</a>

最常见的解决方案是创建一个表单并这样做:

@using (Html.BeginForm("DeleteConfirmed", "Cars", new { id = item.Id }))
 {
   @Html.AntiForgeryToken()
   <input type="submit" value="&#xf00d;" class="btn btn-danger" onclick="return confirm('Are sure wants to delete?');" />
 }

有没有一种不需要使用表单的方法?

【问题讨论】:

  • 删除操作正在更改数据,因此它应该始终是[HttpPost](或[HttpDelete])方法,因此您应该使用表单,而不是链接(生成 GET)。为什么不想要表格?
  • 您想要实现的是从客户端发出异步请求。您可以将异步调用 Delete 操作方法的 javascript 函数绑定到视图中的按钮单击。查看this question 以获取有关如何执行此操作的示例。

标签: asp.net-mvc


【解决方案1】:

是的。请参考以下代码:

输入类型="button" id="btnDelete" class="btn btn-danger" 值="删除" />

<script type="text/javascript">
    $("#btnDelete").click(function () {
        $.ajax({
            url: "/Cars/Delete",
            type: 'POST',
            data: { id='-your-id' },
            async: 'true',
            dataType: 'html',
            success: function (data) {
                //Do your thing on Success if needed
            }
        });
    });
</script>

【讨论】:

    猜你喜欢
    • 2011-04-16
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多