1

I'm new with and using ASP.NET, MVC3 and AJAX.

I try to call a method in my controller with an AJAX call, but I receive an Internal Server Error.

Here's my Javascript method:

function DeleteItem(id) {
  var answer = confirm("Are you sure ?")
  if(answer) {
    $.ajax({
      type: 'POST',
      url: '/Item/Delete',
      data: id,
      dataType: 'json',
      success: function (data) {
        alert('Function called');
      },
      error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
      }
    });
  }
}

and here's my method in my Controller:

public ActionResult Delete(int idItem) {
  Item.Delete(idItem); //delete my item
  return RedirectToAction("Index", "Item");
}

The Javascript method is called, but when I answer "Yes, I'm sure I want to delete", I get an Internal Server Error and I am not sure why. What causes the server error?

pnuts
  • 58,317
  • 11
  • 87
  • 139
AlexB
  • 7,302
  • 12
  • 56
  • 74

3 Answers3

1

My guess is that the reason you are getting an internal server is because the name of the int that you are passing in does not match the int that you are expecting in your controller. As a result, idItem is most likely null which is causing your internal server error when going to delete.

Change the data to match

function DeleteItem(id) {
    var answer = confirm("Are you sure ?")
    if (answer) {
        $.ajax({
            type: 'POST',
            url: '/Item/Delete',
            data: { idItem: id},
            dataType: 'json',
            success: function (data) {
                alert('Function called');
            },
            error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
            }
        });
    }
}
David L
  • 32,885
  • 8
  • 62
  • 93
0

Your ActionResult method does not have the [HttpPost] attribute. Your Ajax call is of type 'POST'.

Oliver
  • 8,794
  • 2
  • 40
  • 60
0

Perhaps you need to serialize the id you are passing to action to JSON format. And you also need to decorate your action method with [HttpPost] attribute so that it accepts POST verbs.

Alexander Tsvetkov
  • 1,649
  • 14
  • 24