I am trying to get my head around ASP MVC with using AJAX requests to the C# controller, as it stands; I am able to call my controller from my AJAX request. However I'm struggling to return the results I'm looking for.
Overall I'm attempting to get some data from the database and return it as an array to JavaScript. What would be fantastic is if in JavaScript I could access the data in a format such as array["key"]
using an associative array.
However, this is what I am encountering with my AJAX request, Initially I call the controller from my AJAX.
$.ajax({
type: "POST",
url: "/booking/getParks",
dataType: "JSON",
async: false,
success: function (data) {
alert(data.data);
}
});
This calls my very simple function in my booking controller as you can see below.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult getParks(string stylesheet)
{
var parks = Database.Open("SQLServerConnectionString").Query("SELECT * FROM Park");
return Json(new { data = parks });
}
Now when I alert in the JavaScript AJAX success function you can see I call the data.data
, this outputs the following:
Now, if I was to reference data.data[0]
, this would output [object Object]
and if I was to further reference data.data[0]["id"]
which in my case I would expect an output of 1. Instead I receive undefined
.
Now, I'm guessing that this has something to do with the way that I am returning a C# dynamic.
However, I am presuming that I am returning the Object to AJAX incorrectly.
How can I return the values so that they are an associative array in JavaScript? Or even a method in which I can receive the data and convert it JavaScript side maybe...
Thank you.
EDIT:
alert(JSON.stringify(data));
Returns:
alert(JSON.stringify(data));