0

I am new in learning jQuery, Json, Ajax.. and am trying to understand the concepts clearly, but having a little difficult time.

I have a ajax POST Delete method which is working, but my prof. has asked me to refactor the code in my Controller to better the overall performance.

This is my Delete in Controller

// POST: Course/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Course course = courseService.GetCourseByID(id);           
            courseService.DeleteCourse(id);

            return RedirectToAction("Index");
        }

And my ajax call

$('#dialog-box').on("click", '#confirm-del', function () {

            var token = $('input[name="__RequestVerificationToken"]').val();
            var data = { id: id, __RequestVerificationToken: token };

            $.ajax({
                type: "POST",
                url: "@Url.Action("Delete","Course")",
                data: data,
                //ajaxasync: true,
                success: function () {
                    $("#dialog").dialog("close");
                    $('div.table-content').empty().load('.table-content');
                    //console.log("success");
                },
                error: function () {
                    console.log("failed");
                }
            });
        });

My prof. commented saying "Delete Post ajax calls reloads page or goes to ajax? It looks like it reloads. Change color of some element in ajax to confirm it goes to the ajax call. It's unnecessary and if you have more logic after the ajax returns, you won't be able to do anything since you just reloaded the page."

And this was after asking for a clarification on what to do as I am not being able to fully comprehend the issue.

If I just return View() instead of the return RedirectToAction (Index) will it be better performance and take care of the issue the prof. is talking about?

Truecolor
  • 437
  • 2
  • 6
  • 22
  • It doesn't sound like your instructor is talking about your server-side code, he's talking about your client-side code. He's asking you to perform some visible change in the callback for your AJAX in JavaScript to confirm that the AJAX call was successful without reloading the page. (Because if the page reloads then that visible change won't be there anymore.) – David Mar 10 '17 at 15:06

2 Answers2

1

Your professor is correct. You should not use RedirectToAction if you plan to call that Action Method via Ajax.

Instead, you need to return JsonResult. For example,

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    Course course = courseService.GetCourseByID(id);
    courseService.DeleteCourse(id);

    return Json("Course was deleted successfully.");
}

FYI: if you really need to redirect to different page inside Ajax call in some rare cases, you can use JavaScriptResult.

Community
  • 1
  • 1
Win
  • 61,100
  • 13
  • 102
  • 181
  • I am doing an `.empty().load(' ..')` in my Ajax to refresh the table automatically after the deletion. Will it be an issue? – Truecolor Mar 10 '17 at 15:33
  • It should not be an issue as long as *DeleteConfirmed* method returns *JsonResult*. – Win Mar 10 '17 at 15:39
  • I apologize if this is stupid question, but how will I know it is returning the JsonResult? I mean the the deletion is working, but I am not seeing the message "Course was deleted successfully" on the page, if that's what I am supposed to see on the page after deletion. – Truecolor Mar 10 '17 at 15:42
  • If you want to see `Course was deleted successfully.` message, you will need to add a parameter in success function. For example, `success: function (result) { console.log(result); }` – Win Mar 10 '17 at 15:45
  • That's what I was thinking. Got it. Thanks a lot for the help & explanation. – Truecolor Mar 10 '17 at 15:50
0

return RedirectToAction("Index"); returns HTTP status 302 with the URL to redirect (Home/Index) in your case.

Since you are not handling this HTTP status in ajax handler (success handles 2XX codes and error 4XX and 5XX codes) the response is not handled on client side at all

Alex Art.
  • 8,711
  • 3
  • 29
  • 47
  • Sorry, but I am now more confused with the client side and server side aspects. Is it my ajax call that's the issue? – Truecolor Mar 10 '17 at 15:12
  • 1
    ajax on client side calls the server -> server responds with redirect result HTTP status 302 -> ajax handler doesn't know how to handle this response – Alex Art. Mar 10 '17 at 15:15