Reputation: 584
On the server side I create a list
List<object> data = new List<object>();
for (var j = 0; j < items.Count(); j++)
{
var temp = groups.Where(customfilter);
data.Add(Html.Raw(Json.Encode(temp)));
}
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
var serializedData = serializer.Serialize(data);
Inside Javascript the folowing won't work for anything but primitive types.
var localData = @data;
This is the error:
System.Collections.Generic.List`1[System.Object]
What am I missing?
Upvotes: 3
Views: 4330
Reputation: 978
I am assuming that the C# code you posted is a Controller action method.
You would need to have your controller method return a JsonResult, and then use a JSON library to deserialize it.
Something like
public class MyController: Controller
{
public JsonResult MyAction ()
{
var data = new List<object>();
for (var j = 0; j < items.Count(); j++)
{
var temp = groups.Where(customfilter);
data.Add(temp);
}
return Json (data, JsonRequestBehavior.AllowGet);
}
}
Note how you don't need to serialize every item as you add it to the list.
From the client side, you can call your method and deserialize the result to a list. You can do it like this:
$.ajax ({ url:'/My/MyAction'}).done (function (data) {
var myList = JSON.parse (data);
});
Edit:
After some testing, I found that you can access the data by doing:
var myList = data;
Not sure why, but "data" is sent directly as an array.
Hope it helps!
Upvotes: 1
Reputation: 19504
First of all check this link http://james.newtonking.com/pages/json-net.aspx
Second
var temp = groups.Where(customfilter).ToList();
If you use where cast it to list or it will be something like Query object *(I dont remember exactly type) Or if you want to select one object try groups.FirstOrDefault
Third
data.Add(temp);
Serializer will do his job to convert it.
Upvotes: 0