Saturday, May 16, 2015

jQuery AJAX 500 Error with ASP.NET MVC


Just wanted to drop a quick note for anyone using jQuery with ASP.NET MVC and experiencing 500 Internal Server errors when debugging with the browser's network monitoring feature.

In order to send a proper AJAX call with jQuery's $.ajax function, you must use JSON.stringify . Suppose you are sending one field to the MVC backend.

var data = $('#inputBox').val();
  method: "POST",
  url: "@Url.Action("ActionName", "ControllerName")",
  data: JSON.stringify({"data" : data }),
  success: function (data) {
    if (data.valid)
        alert('Success:' + data.message);

In the ControllerName controller,

public JsonResult ActionName(string data) {
  // do something with data
  return Json(new { valid = true, message = "Success" });

Basically, if you receive a 500 error from the server but are never able to hit a break point in Visual Studio, look at the way the data is sent and the way the data is received. More likely than not there is an error with the data or dataType or mimeType parameters (cross-domain requests are a different beast too).

The key difference is the difference between a JSON string and a JavaScript object. JSON strings aren't JavaScript objects just because they look like JavaScript objects; they have a stricter syntax. It is not a limitation or error of ASP.NET MVC or the backend if it refuses to parse incorrectly formed JSON.

Thanks for visiting and comments are welcome.

1 comment:

  1. Hi everyone! I think like this article is indeed helpful for me, as the actions I took were really essential and effortful.