Reputation: 469
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?
Upvotes: 0
Views: 489
Reputation: 62280
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.
Upvotes: 1
Reputation: 8781
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
Upvotes: 0