So I have a json that calls a JsonResult
The class:
public class Client{
public int Id {get;set;}
public string Name {get;set;}
}
The action being called:
public JsonResult Index(int Id)
{
var a = context.Clients.ToList();
return Json(a, JsonRequestBehavior.AllowGet);
}
this is the call
<script type="text/javascript">
$(document).ready(function () {
var link;
$('a.client-list').click(function () {
link= $(this);
$.ajax({
url: '/client/index?Id=4455',
dataType: 'json',
success: function (data) {
$.each(data, function (id, val) {
alert(id.toString() + ' ' + val.toString());
});
}
});
return false;
});
});
</script>
So my problem is, I know that it returns something cuz it loops through the alert that I put in. but the value that pops out is this
0 [object Object]
1 [object Object]
I’m not sure why it’s not reading it properly. The values queried btw are
1 TestCompany1
2 TestCompany2
Am I missing something on the jquery??
Update your $.each like so:
You are returning a collection (
Array) of the Client type. The$.eachfunction will provide the index of the array and the item in the array associated with the index. In this case, each item in the array will be a ClientObject. More information on$.eachhere: http://api.jquery.com/jQuery.each/Fore more details when debugging JavaScript, try using the console:
Just hit F12 in your browser (PC) and select the console tab. You will be able to see more detail about the
Objectincluding its properties.