Reputation: 45
I have a simple C# Class, called Employee which has two properties, Name, Age. I need to create a list of employees and serialize into JSON and access in jquery.
I have successfuly converted in to JSON. But i stuck with retreive through the Jquery.
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
IList<Employee> employeeList = new List<Employee>() {
new Employee() { Name = "XXX", Age=20},
new Employee() { Name = "YYY", Age=24}
new Employee() { Name = "kamal", Age=24}
};
System.Web.Script.Serialization.JavaScriptSerializer objectSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonObj = objectSerializer.Serialize(employeeList);
Response.Write(jsonObj);
}
Any idea..??
Thank in advance.
Upvotes: 1
Views: 188
Reputation: 69915
You should write the json object in a script tag and assign it to some variable in order to use it. Try this
Response.Write("<script type='text\javascript\> var employeeObj = "+jsonObj+"</script>");
Usage in jQuery
//Looping through employeeObj using each method. Inside each this points to each item in the array and you can use this.Name and this.Age to retreive the values.
$.each(employeeObj, function(){
alert("Name: " + this.Name + " Age: "+ this.Age);
});
Upvotes: 1
Reputation: 4764
Use the javascript file and use
var jsonObject = JSON.parse(string);
Upvotes: 0
Reputation: 13756
$.ajax(
{url: "your url to get data",
type="get",
dataType: "json",
success: function(data) { //data is your json
}
);
that is ajax call, but if you want to access it as variable you should write it through c# like this
String.Format("<script language="javascript">
var myJson = {0};
</script>", jsonObj)
Then you can access it from javascript like
myJson;
Upvotes: 0