Wasim Qadir Wasim Qadir - 6 months ago 12
jQuery Question

Access array of server side in jQuery

I have a pie chart for which I want to populate the data. I have been able to set the data in jQuery like this

var data = [
{ label: "Abc", data: 12 },
{ label: "xyz", data: 15 },
{ label: "Setwet", data: 85 },
{ label: "DashOut", data: 30 },
];


I want to be able to set the same data from my code behind file from database, and access it in jQuery. How can I do that?

My database does have all the information. I have created a class with two members label and data. I have created a collection of this class and added values from database table to this collection like this

private List<myData> _myData;
public List<myData> MyData
{
get
{
if (_myData == null)
{
_myData = new List<myData>();
_myData.Add(new myData() { label = "abc", data = "10" });
_myData.Add(new myData() { label = "def", data = "20" });
}
return _myData;
}
set { _myData = value; }
}


My jQuery is expecting an array but in code i have created a Collection of user defined class. Will that be ok? or how should I go about it?

Answer

There are several forms to do this. Can convert (serialize) MyData to json using JavaScriptSerializer and save in hidden field:

hiddenfield.Value = new JavaScriptSerializer().Serialize(MyData)

then, can access to this from client-side:

var data = $("hiddenfield").val();

Can use WebMethod and use javascript from server-side.