JSON Object render from Server Side using C#
02:24
On the server you need to serialize the data as JSON so that you can pass it to the client side (Browser).
First of all we need a Data Model, So i'm creating a class for this.
Now fill this Data Model
Page load code will be,
Now code at the client side (inside .aspx) will be
The Final Result is,
First of all we need a Data Model, So i'm creating a class for this.
public class TestClass
{
public int UserID { get; set; }
public string Fullname { get; set; }
public string EmailAddress { get; set; }
}
Now fill this Data Model
private static List<testclass> FillDataModel()
{
List<testclass> testList = new List<testclass>();
for (int i = 0; i < 10; i++)
{
TestClass test = new TestClass();
test.UserID = i;
test.Fullname = "Name " + (i + 1);
test.EmailAddress = (i + 1) + "@yahoo.com";
testList.Add(test);
}
return testList;
}
Page load code will be,
List<testclass> testList = FillDataModel();
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(testList);
HiddenField jsonField = new HiddenField
{
ID = "data"
};
jsonField.Value = json;
this.Form.Controls.Add(jsonField);
Now code at the client side (inside .aspx) will be
function LetsTestJson()
{
var field = document.getElementById('data');
var data = JSON.parse(field.value);
for (var i = 0; i < data.length; i++) {
var values = "ID : " + data[i].UserID + "\nFull Name : " + data[i].Fullname + "\nEmail : " + data[i].EmailAddress;
alert(values);
}
}
Input Button
The Final Result is,

0 comments: