【问题标题】:How do I call an Ajax Delete in ASP.NET MVC?如何在 ASP.NET MVC 中调用 Ajax Delete?
【发布时间】:2020-02-28 03:10:58
【问题描述】:

我正在使用现有的 MVC5 网络应用程序。我们有一个带有删除图标的典型索引页面,但没有删除视图。我们在索引页面的脚本部分中有一个 Ajax Post 删除。 我是 Ajax 的新手,所以我在这方面有点过头了,所以这可能是我缺少的一些非常基本的东西。

但这里是:


$.ajax({
type: "POST",
url: '@Url.Action("DeleteRecord")',
data: data,
success: function (data) {
if (!data) {
                    doPopStatus("ERROR", "Something went haywire in the submit. Try Again.", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
                                }
                  else if (data.success === true) {
doPopStatus("Success!", "The record has been removed.", "modal-header alert-success", "fa fa-check-circle text-success", "alert", "text-primary", '@Url.Action("Index")');
                                }
                  else { //if (data.isSuccessful === false) {
               doPopStatus("Delete Failed!", data.status, "modal-header alert-danger", "fa fa-exclamation-triangle text-warning", "alert", "text-danger");
                                }
                            },
error: function (jqXHR, textStatus, errorThrown) {
goReady();
                  console.error(jqXHR);
                  let errorDetails = doParseResponseErrorDetails(jqXHR);
doPopStatus("ERROR", "Something went haywire in the post. Try Again.<p>" + jqXHR.status + ": " + jqXHR.statusText + "<br />" + '<div class="bs-callout bs-callout-danger">' + errorDetails + "</div></p>", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
    }});


这是索引页面中的代码(之前):

<a id="hlnkDelete" href='@Url.Action("DeleteRecord", new { id = item.ID })' data-id='@item.ID' title="delete record" class="text-red"><i class="fa fa-trash"></i></a>

最后是控制器方法中的代码:

        [HttpPost]
        public ActionResult DeleteRecord(int id)
        {
            Capture capture = db.Captures.Find(id);
            if (capture == null)
                return Json(new { success = false, status = "Invalid ID!" }, JsonRequestBehavior.AllowGet);

            try
            {
                db.Captures.Remove(capture);
                db.SaveChanges(User.Identity.Name);

                return Json(new { success = true, status = "Record Deleted" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Exceptions.Handler.HandleException(ex, System.Web.HttpContext.Current.Request);
                return Json(new { success = false, status = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

Delete 或 DeleteRecord 没有视图,但此代码在同一站点的其他页面中有效。

在我看来它应该都可以正常工作,并且我们在其他页面中有类似的代码可以正常工作。 Ajax 函数是“DeleteRecord”,Index 页面前面的代码调用了“DeleteRecord”,我们在 Controller 中将函数命名为“DeleteRecord”。

然而这是我们得到的错误:

Exception: A public action method 'DeleteRecord' was not found on controller 'DemographicsDatabase.Controllers.CapturesController'.
Controller: Captures
Action: DeleteRecord 

我在这里做错了什么,或者没有看到?

【问题讨论】:

  • 上面的错误是控制台显示的还是页面显示的?我无法确定 ajax 函数是否正确绑定到按钮。

标签: ajax asp.net-mvc controller asp.net-ajax


【解决方案1】:

此按钮不会调用 ajax 函数。

<a id="hlnkDelete" href='@Url.Action("DeleteRecord", new { id = item.ID })' data-id='@item.ID' title="delete record" class="text-red">
   <i class="fa fa-trash"></i>
</a>

你必须像这样绑定事件;

  1. 删除 html 中的 href 属性。然后添加一个btnDelete 类,我们稍后将使用它。
<a id="hlnkDelete" data-id='@item.ID' title="delete record" class="text-red btnDelete"><i class="fa fa-trash"></i></a>
  1. 请务必将脚本放在正文标记下方。然后,在您的脚本中,绑定事件;
<script>
   $(document).ready(function(){
      $(document).on("click", ".btnDelete",function(){

         var data = $(this).data("id");

         $.ajax({
            type: "POST",
            url: '@Url.Action("DeleteRecord")',
            data: data,
            success: function (data) {
               if (!data) {
                  doPopStatus("ERROR", "Something went haywire in the submit. Try Again.", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
               }
               else if (data.success === true) {
                  doPopStatus("Success!", "The record has been removed.", "modal-header alert-success", "fa fa-check-circle text-success", "alert", "text-primary", '@Url.Action("Index")');
               }
               else { //if (data.isSuccessful === false) {
                  doPopStatus("Delete Failed!", data.status, "modal-header alert-danger", "fa fa-exclamation-triangle text-warning", "alert", "text-danger");
               }
            },
            error: function (jqXHR, textStatus, errorThrown) {
               goReady();
               console.error(jqXHR);
               let errorDetails = doParseResponseErrorDetails(jqXHR);
               doPopStatus("ERROR", "Something went haywire in the post. Try Again.<p>" + jqXHR.status + ": " + jqXHR.statusText + "<br />" + '<div class="bs-callout bs-callout-danger">' + errorDetails + "</div></p>", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
            }
         });

      });
   });
</script>

【讨论】:

    【解决方案2】:

    我可以建议您进行以下修改。尽可能少地保持项目中的代码有点相似。

    // Put the Ajax call in a function
    let deleteRecord = function(itemId){
        $.ajax({
        type: "POST",
        url: '@Url.Action("DeleteRecord")',
        data: {id: itemId},
        success: function (data) {
          if (!data) {
            doPopStatus("ERROR", "Something went haywire in the submit. Try Again.", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
          } else if (data.success === true) {
            doPopStatus("Success!", "The record has been removed.", "modal-header alert-success", "fa fa-check-circle text-success", "alert", "text-primary", '@Url.Action("Index")');
          } else { 
            //if (data.isSuccessful === false) {
            doPopStatus("Delete Failed!", data.status, "modal-header alert-danger", "fa fa-exclamation-triangle text-warning", "alert", "text-danger");
          }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            goReady();
            console.error(jqXHR);
            let errorDetails = doParseResponseErrorDetails(jqXHR);
            doPopStatus("ERROR", "Something went haywire in the post. Try Again.<p>" + jqXHR.status + ": " + jqXHR.statusText + "<br />" + '<div class="bs-callout bs-callout-danger">' + errorDetails + "</div></p>", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
        }
       });
    }
    

    在你看来

    <a id="hlnkDelete" href='javascript:deleteRecord(@item.ID)' data-id='@item.ID' title="delete record" class="text-red"><i class="fa fa-trash"></i></a>
    

    希望对您有所帮助!

    【讨论】:

    • 谢谢,但不幸的是,垃圾桶图标什么也没做。
    【解决方案3】:

    更新您的锚标记并添加此功能并检查

    <a href="javascript://" title="delete record" class="text-red" onclick="DeleteCaptureRecord('@item.ID')"><i class="fa fa-trash"></i></a>
    
    
    function DeleteCaptureRecord(itemId)
    {
     $.ajax({
    type: "POST",
        url: '@Url.Action("DeleteRecord","Captures")',
        data: {"id": parseInt(itemId)},
        success: function (data) {
    if (data != null && data.success) {
    doPopStatus("ERROR", data.status , "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
          } else { 
     doPopStatus("Success!", data.status, "modal-header alert-success", "fa fa-check-circle text-success", "alert", "text-primary", '@Url.Action("Index")');
    }
        },
        error: function (response) {
      goReady();
    doPopStatus("ERROR", "Something went haywire in the post. Try Again.<p>" + jqXHR.status + ": " + jqXHR.statusText + "<br />" + '<div class="bs-callout bs-callout-danger">' + errorDetails + "</div></p>", "modal-header alert-danger", "fa fa-exclamation-circle text-danger", "alert", "text-danger");
        }
       });
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-23
      • 1970-01-01
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      相关资源
      最近更新 更多