views:

151

answers:

5

I am using the ASP.NET command

var returnValue = new JsonResult { Data = items.Skip((pageNumber - 1) * pageSize).Take(pageSize) };

return returnValue;

to return the paged contents of a table via JSON, but when I got to try to parse it, in jQuery, the $.each takes each character as an individual element.

The output from that is along the lines of

[{"ItemNumber":1,"Description":"Description1"}, {"ItemNumber":2,"Description":"Description2"}]

listing all the rows and fields correctly. However this doesn't look like correctly formatted JSON to me (I beleive it should be encased in {}), is it?

If not what should I be doing to correctly output the table? If so, how can I loop round each element in jQuery, and extract the field values?

+1  A: 

This is correctly formatted JSON.

You could try evaluating it with

var someVar = eval(jsonValue);

but this may lead to XSS.

Or even use this plugin.

This question may be related too.

wtaniguchi
$.getJSON sorted it out. Are there any known issues with using that (I thought I had read somewhere someone saying not to use it)?
Mad Halfling
No, since I believe this method sanitizes your response before parsing it.
wtaniguchi
A: 

Actually, using eval might be dangerous: unlike the case when it's enclosed in {}, it's possible to subvert the construction of an array. This occurs when eval tries to create an array using the Array constructor. See this post.

If you're not worried about that, you can use eval - for safety, the JQuery plugin in wtaniguchi's answer.

Vinay Sajip
Yeah, I personally never use eval to evaluate JS. I won't how safe json evaluation methods didn't get to jQuery core.
wtaniguchi
A: 

Can you not loop through like this?

for (i = 0; i <= returnValue.length - 1; i++){
   //access your properties like this:
   returnValue[i].ItemNumber;
   returnValue[i].Description;
}

I don't know if using JsonResult will work like that, but if you return a list of objects in your server side code, it will work like that. Assuming you're using Asp.Net AJAX it will serialize automatically.

Chad
A: 

As far as I know there exists also the following json deserializer in Asp.net Ajax:

Sys.Serialization.JavaScriptSerializer.deserialize(...)

You'd have to browse for the exact usage since I don't know it by heard now.

Juri
A: 

I use the AJAX.NET function Sys.Serialization.JavaScriptSerializer.deserialize to get my JSON data when I've created it using System.Web.Script.Serialization.JavaScriptSerializer.Serialize.

Tim