Reputation: 2754
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??
Upvotes: 0
Views: 4130
Reputation: 12440
Update your $.each like so:
$.each( data, function (index, client ) {
alert( client.Id + ' ' + client.Name );
});
You are returning a collection (Array
) of the Client type. The $.each
function 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 Client Object
. More information on $.each
here: http://api.jquery.com/jQuery.each/
Fore more details when debugging JavaScript, try using the console:
$.each(data, function ( index, client ) {
console.log( client );
});
Just hit F12 in your browser (PC) and select the console tab. You will be able to see more detail about the Object
including its properties.
Upvotes: 4