如何在ASP.NET MVC中调用Ajax删除?

问题描述 投票:0回答:3

我正在使用现有的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”,索引页面前面的代码称为“ DeleteRecord”,我们在Controller中将函数命名为“ DeleteRecord”。

但是这是我们得到的错误:

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

我在这里做什么错了,还是没看见?

ajax asp.net-mvc controller asp.net-ajax
3个回答
0
投票

此按钮不会调用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. 请确保将脚本放在body标签下面。然后,在脚本中绑定事件;
<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>

0
投票

我可以建议您进行以下修改。为了使您的代码在整个项目中保持相似,请尽可能减少。

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

希望获得帮助!


0
投票

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

<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");
    }
   });
}
© www.soinside.com 2019 - 2024. All rights reserved.