Using Java Script in Asp.Net

Started by thiruvasagamani, Aug 30, 2008, 09:34 PM

Previous topic - Next topic

thiruvasagamani

Introduction:

Asp.net provides many server controls which ease the development process for the developer. These controls include input controls like TextBoxes, Button controls and complex controls like DataGrid and Calendar.

All the server controls have one common process which is known as postback. Postback is when we send the request from the user back to the server and than server takes some action on it and returns the call back to the client.

Sometimes these calls are very expensive and we rather solve the problem on the client side. In this article we will see that how we can use the client side operations with the server controls and make less use of the round trips.

Using the client script with the Asp.net server controls:

There are number of ways that you can use the client side script with the Asp.net server controls. You can with code it in the code behind file or you can have a separate .js file which stores the client side script. In this article we will code most of the scripts in the code behind file.

Popping a simple alert box using the button click event:

Now let's see the code which has achieved this:

private void Page_Load(object sender, System.EventArgs e)
{

if(!Page.IsPostBack)
{

Button1.Attributes.Add("onclick","alert('Hello World')");

}

}

   As you can see that popping a simple message box is very easy. Let's see another way of doing the same thing. But this time we will make a small function that will pop us the message box. You can use the string variable to hold the complete javascript. But its not a good idea to concatenate string again and again since as you know string is immutable which means that each time you concatenate something in that string it will make a new string using memory again and again. That's why I am using StringBuilder object which is like a link list and will be made only one time.

private void Page_Load(object sender, System.EventArgs e)
{

if(!Page.IsPostBack)
{

StringBuilder str = new StringBuilder();

str.Append("<script language=javascript>");

str.Append("function PopWindow()");

str.Append("{");

str.Append("alert('hello world')");

str.Append("}");

str.Append("</script>");

if(!Page.IsClientScriptBlockRegistered("clientscript"))

{

Page.RegisterClientScriptBlock("clientscript",str.ToString());

}

Button1.Attributes.Add("onclick","PopWindow();");

}

}
Thiruvasakamani Karnan