开发者

Using jQuery to Read JSON Returned from ASP.NET

开发者 https://www.devze.com 2023-03-29 01:15 出处:网络
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 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.


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);
});


$.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;


Json.js

Use the javascript file and use

var jsonObject = JSON.parse(string);
0

精彩评论

暂无评论...
验证码 换一张
取 消