Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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:

enter image description here

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:

enter image description here

share|improve this question
    
Alert json as string to see what's in it: alert(JSON.stringify(data)); –  Ehsan Sajjad Mar 6 at 13:49
    
What's the data type of parks? DataSet? Custom Entity Class? –  Tseng Mar 6 at 13:50
    
@EhsanSajjad - I Edited the post with the JSON stringify reponse. –  mdixon18 Mar 6 at 13:53
    
@Tseng parks is a IENumerable<dynamic> –  mdixon18 Mar 6 at 13:53
    
From the stringify result it looks more like you are returning a table or list if tables –  Tseng Mar 6 at 13:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.