user3654442 user3654442 - 7 months ago 341
Javascript Question

Jquery ajax call to pass JSON array in MVC (500 internal server error)

Here is my ajax that is being invoked as a function when an array has data.

function sendDataToController() {
$.ajax({
type: 'POST',
url: '/Home/Results',
cache: false,
traditional: true,
contentType: "application/json",
data: { FormData : exampleFormData },
success: function (data) {
alert("sent data to controller")
},
error: function (data) {
alert("Error " + data.responseText);
}
});
}


The array looks like this:

var exampleFormData = [];


And the JSON looks like this currently with some more data but shortened for display purposes.

"[{\"Birthdate\":\"1947-03-21\",\"ROWID\":\"000001\",\"SpecCodes\":\"987654\"}]"


This JSON is being pushed into the array multiple times before using ajax to send to the controller.

exampleFormData.push(jsonData);


The control that this is being passed into looks like this:

public ActionResult Results(string exampleFormData)
{
var formDataList = JsonConvert.DeserializeObject<List<SampleFormData>>(exampleFormData);

return View();

}


And here is the class that models that "SampleFormData" list

public class SampleFormData
{
public string Birthdate { get; set; }
public string ROWID { get; set; }
public string Score { get; set; }
public string SpecCodes { get; set; }

}


As is, this produces a 500 internal server error. Can anyone provide any input on what is being done incorrectly here?

Answer

There are a few things to consider with the code you provided that could be causing your issue.

Ensuring You Can Post Properly

In order for your Controller to actually acknowledge the jQuery call, you'll need to ensure that the Controller Action is decorated with the [HttpPost] attribute, indicating it should be used for POST calls :

[HttpPost]
public ActionResult ExamineeResults(string exampleFormData)
{
    // Your code here
}

Ensuring You Are Targeting The Proper Action

Your AJAX call currently is targeting Home/Results, however the name of your actual Controller Action is ExamineeResults. Unless you have some specific routing rules in place, you should use the existing name to make sure you target it correctly :

url: '/Home/ExamineeResults',

Additionally, if you have this within your View, you can use the Url.Action() method to resolve the proper location :

url: '@Url.Action("ExamineeResults","Home")'

Using Proper Parameters

MVC will only know how to properly map data as you specify it. Currently you are posting your contents as such :

data: { FormData : exampleFormData },

This means that the name of your parameter in your Controller Action should match that exactly (i.e. FormData instead of exampleFormData) :

public ActionResult ExamineeResults(string FormData)

Putting All Of These Together

You should be able to resolve this by updating your code as follows :

$.ajax({
            type: 'POST',
            // Use Url.Action() to resolve the proper URL
            url: '@Url.Action("ExamineeResults","Home")',
            cache: false,
            // Use JSON.parse() to serialize your content to send accross
            data: { formData: JSON.parse(exampleFormData) },
            success: function (data) {
                alert("sent data to controller")
            },
            error: function (data) {
                alert("Error " + data.responseText);
            }
        });

along with the following Controller Action :

[HttpPost]
// You can let MVC perform the binding for your by mapping your content
// to an array of your SampleFormData objects
public ActionResult ExamineeResults(SampleFormData[] formData)
{
      // Do your thing here (as formData is already serialized)
      return View();
}

You can see an example of this here and demonstrated below :

enter image description here

Comments