简体   繁体   中英

Ajax call returns internal 500 error

Hi I am trying to execute an ajax call to the server but I seem to have no luck I keep getting back on the console an error 500 Internal server error.This is my ajax call:

    $("body").on("click", "#ok", function (e) {
    var id = $(this).attr("data-bookid");
    $.ajax({
        url: "/ProductEditor/DeleteBook",
        type:"POST",
        data: { bookId: parseInt(id) },
        success: function (data) {
            console.log(data);
        },
        error: function (data) {
            console.log(data);
        }
    });
    e.preventDefault();
})

And this is the C# code I am trying to call:

public ActionResult DeleteBook(int bookId)
{
   bookRepository.DeleteBook(bookId);
   return RedirectToAction("Books", "ProductManager");
}

While trying to debug I have noticed that the DeleteBook method is not even called.

What am I doing wrong?

EDIT I have added the [HttpPost] attribute but it still does not work

Without more information, it's not easy to tell you what you are doing wrong.

However, the error function callback for the jQuery ajax function takes three parameters:

(jqXHR, textStatus, errorThrown)

$.ajax({
    url: "/ProductEditor/DeleteBook",
    type:"POST",
    data: { bookId: parseInt(id) },
    success: function (data) {
        console.log(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});

The third parameter, errorThrown will have the HTTP response text for the call to /ProductEditor/DeleteBook . I would suggest looking at what errorThrown is showing, as well as possibly running the entire program in debug mode.

Perhaps var id = $(this).attr("data-bookid"); is incorrect, and the value of id is being set to undefined ?

Also, you can use the Network tab in the F12 Development Tools in IE or Chrome, Firebug in Firefox, or Fiddler to debug ajax calls. You can watch the ajax request being sent to the server as well as the response from the server in order to see whether the correct data ( bookId ) is being sent in the correct format (JSON) and what the response is from the server

Add HttpPost to your method and try

[HttpPost]
public ActionResult DeleteBook(int bookId)
{
   bookRepository.DeleteBook(bookId);
   return RedirectToAction("Books", "ProductManager");
}

Your WebMethod must be static

[WebMethod(true)]
public static ActionResult DeleteBook(int bookId) 
{    
     bookRepository.DeleteBook(bookId);    
     return RedirectToAction("Books", "ProductManager"); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM