1

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.

1
  • 1
    Do you have anything with jQuery so far? You might want to look at jQuery.getJSON. Commented Aug 19, 2011 at 12:09

3 Answers 3

1

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Where are you trying to use this object?
0
$.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;

Comments

0

Json.js

Use the javascript file and use

var jsonObject = JSON.parse(string);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.