Как мне вызвать Ajax Delete в ASP. NET MVC? - PullRequest
0 голосов
/ 28 февраля 2020

Я работаю с существующим веб-приложением MVC5. У нас есть типичная страница указателя со значком удаления, за исключением отсутствия представления «Удалить». У нас есть Ajax Post delete в разделе скриптов на странице индекса. Я новичок в 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», и мы назвали функцию «DeleteRecord» в контроллере.

И все же мы получаем эту ошибку:

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

Что я здесь не так делаю или не вижу?

Ответы [ 3 ]

0 голосов
/ 28 февраля 2020

Могу ли я предложить вам следующую модификацию. Это как можно меньше, чтобы сохранить ваш код в проекте немного похожим.

// 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 голосов
/ 28 февраля 2020

Обновите свой якорный тег и добавьте эту функцию и отметьте

<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");
    }
   });
}
0 голосов
/ 28 февраля 2020

Эта кнопка не будет вызывать функцию 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. Удалите атрибут href в вашем html. Затем добавьте класс btnDelete, который мы будем использовать позже.
<a id="hlnkDelete" data-id='@item.ID' title="delete record" class="text-red btnDelete"><i class="fa fa-trash"></i></a>
Обязательно поместите скрипт под тегом 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>
...