Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Monday, July 13, 2015

ASP.NET MVC Call Controller with jQuery $.ajax and Return PartialViewResult

Hi,

Didn't find a one-stop answer to this question, so here it is:

"How do I POST JSON to an ASP.NET MVC controller?"

It's actually quite simple. Follow the following steps.

1. Create a model to represent the data structure you want to POST



2. Create a controller method to represent the endpoint you want to contact



3. Create the following jQuery call to make an AJAX call from the frontend to the backend



You can return a PartialViewResult from the controller, and as long as the jQuery AJAX call expects html it will be done.

Hope this helps someone.

Saturday, May 16, 2015

jQuery AJAX 500 Error with ASP.NET MVC

Hi,

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();
$.ajax({
  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.