up vote 1 down vote favorite
share [g+] share [fb]

I am new to JQuery/JSON, and I am trying to get a JSON object returned from one of my MVC action methods onto the client side and display it on screen.

I have been using this tutorial as a reference: http://www.asp.net/ajaxlibrary/jquery_json_data_from_controller.ashx

Here is my action method:

[HttpPost]   
public ActionResult GetStock()   
{
    IStockService service = new DummyStockService();
    return Json(service.GetStock());
}

(GetStock() returns a List of type Stock, where Stock is a plain old C# object with two properties, a string Description and a decimal Price.)

And my client side javascript:

<script type="text/javascript">
$(document).ready(function () {
    $("button").click(function () {
        alert('Line before controller action post');

        //When I get it working I will remove the hardcorded URL
        $.post("http://localhost:3786/Home/Index/GetStock", null, function (data) {
            $.each(data, function (i, item) {

                var displayString = item.Description + ' : ' + item.Price;

                $("<li/>").html(displayString).appendTo("#list");
            });
        });
    });
});
</script>

Currently what is displayed in the #list element is a very long list of "undefined : undefined", as a pose to the description : price pairings. Any ideas are much appreciated.

Edit:

I have now fixed it (although am unable to post an answer for another 7 hours) the issue was that using the hardcoded URL http://localhost:3786/Home/Index/GetStock was not calling the action method correctly, merely outputting the html from /Index/, I changed it to @Url.Action("GetStock") and was away.

Thank you to @Felix for hints on what to look at when debugging.

link|improve this question
1  
I don't see item defined anywhere. Have a look at the structure of the value of data. – Felix Kling Jan 26 at 11:07
my mistake, I was playing around with that $.each loop, changed it back now, same issue. (change reflected in question edit) – Yends Jan 26 at 11:12
Have you checked with fiddler whats being sent over the wire or a javascript debugger like FireBug whats the value of your item object? – Jan Jan 26 at 11:13
1  
Still, no one will be able to help you without knowing the value of data. Maybe the elements have no Description or Price properties. Have a look at it and adjust your code accordingly. – Felix Kling Jan 26 at 11:14
Thanks @Felix, I had a look at the data object, it is a string containing html markup for my html page on which the script resides. Taking a look at why this is now. – Yends Jan 26 at 11:20
feedback

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
or
required, but never shown

Browse other questions tagged or ask your own question.