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.
item
defined anywhere. Have a look at the structure of the value ofdata
. – Felix Kling Jan 26 at 11:07data
. Maybe the elements have noDescription
orPrice
properties. Have a look at it and adjust your code accordingly. – Felix Kling Jan 26 at 11:14