Monday, July 7, 2008

How to use JSON in ASP.NET

JSON is JavaScript Object Notation. Which improve the code readability in java script code and also it help to create object code at client side in ASP.NET. Here you can define your properties and method.

Like

var VariableName=

{

“Property”: value, // Properties

“FunctionName1”:

function(){

//Function body.

},

“FunctionName2”:

function(){

//Function Body.

}

}

If we need any Customer object at client side then we can create like

Var CustomerJSON =

{

“Name”: “Mr Harry”,

“Age”: 23,

“Address”: “10000, Abc Blvd, Los Angeles”,

“Salary”: 300,

“IsRetired”:

function()

{

If (CustomerJSON.Age > 56)

return true;

}

}

You can directly add this JSON script in your ASP.NET page or you can register it by Register client script method of page.

Adding Java script in ASPNet page

Method -1 // In code behind (C# page)

Literal js = new Literal();

js.Text = "<script type='text/javascript' Src= 'CustomerJSON.js'></script>";

this.Header.Controls.Add(js);

Method -2 // in code behind (C# page)

StringBuilder sb = new StringBuilder();

sb.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");

sb.AppendLine(Write your whole JSON code here.);

sb.AppendLine("</script>");

this.ClientScript.RegisterStartupScript(GetType(), "StartupScript", sb.ToString());

Method -3 // in aspx file

Add a new tag for

<script type='text/javascript' Src= 'CustomerJSON.js'></script>

No comments:

Post a Comment