从索引视图直接删除链接,而不是要删除页面

时间:2018-07-22 11:49:34

标签: asp.net-mvc

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

“我的删除控制器”部分:

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

是否有一种不需要使用表格的方式?

1 个答案:

答案 0 :(得分:0)

是的。请参考以下代码:

  

input type =“ button” id =“ btnDelete” class =“ btn btn-danger”   value =“删除” />

<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>