Asp.net Client side Interaction
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:
Let's see how we can pop a simple alert box using a Asp.net Server control.
Below is a simple image of what will happen when you press the button.

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();");
}
}
|
Explanation of the code:
The code is not that hard to understand. We are just appending the java
script on each time. Make sure that you close all the brackets and script tags
or else it will throw exceptions.
We defined a simple function which is called PopWindow() which pops a little
window as an alert box.
Registering the client script is the most important part. If you don't
register the client script block with your application it won't work and it will
throw the exception. First we are checking that if the client side block has
already been registered.
We only register the client side block if the block is not already
registered. Finally, we add the onlclick attributes to the button control and
that's it.
Focusing on a certain control:
If you ever noticed by going to google that google automatically focuses on
the textbox when you visit the page. This is very useful feature which lets the
developer to quickly fill the form. Let's see how we can focus on a textbox
control on the page load.
In the example we will just have a single TextBox on the form which will be
named "TextBox1".
Just type this code in the Body of the Html.
|
<body onload="document.forms[0]['TextBox1'].focus();" MS_POSITIONING="GridLayout">
|
Now if you load the page you will see that the focus is set on the TextBox
control.

Its good to know how the Web Server Control functions but its even more
better to know that how the javascript functions. This will give you more power
over the existing controls.
Using the .js file to keep the javascript functions:
As you might have noticed up till now that when ever you embed the javascript
in the StringBuilder object it will make it larger and larger. If you are using
many javascript functions that it will be a good idea to save all the javascript
functions in a single .js file. This way all the code is present in one place
and it will be easy to make any changes.
Let's see that how we can make the use of the .js files to save our code:
First add the .js file which you will use in your application. Adding a
script file is very simple you can just right click on the project and select
add new item and at the bottom you will see a javascipt file just add that file
and name it as "MyJavaScriptFile".
|
if(!Page.IsPostBack)
{
if(!Page.IsClientScriptBlockRegistered("MyScript"))
{
Page.RegisterClientScriptBlock("MyScript","<SCRIPT Language='JavaScript' src='MyJavaScriptFile.js'></SCRIPT>");
}
Button1.Attributes.Add("onclick","PopWindow();");
}
|
We have done this step in the previous examples. Here a little bit has
changes now we are registering the javafile which is the .js file. And also
remember that .js file only contains the functions and not the whole list of
javascript tags.
Let's take a lot at a simple .js file:
|
function
PopWindow()
{
alert('hello world from the Javascript file');
}
|
As you can see that the PopWindow() is the same as we have used before. By
using this technique we have saved lot of bad coding and lot of code writing in
the code behind file. You should always use the .js file to save your javascript.
Confirmation Boxes using JavaScript:
Let's see how we can add confirmation boxes by the use of the javascript.
Confirmation boxes are used when we need a condition based on yes or no answer.
Let's add such a feature in our application.
Let's first see the JavaScript file which contains the code which will
trigger when we press the button.
|
function
ConfirmationWindow()
{
var result = confirm("Are you sure");
if(result)
{
alert('You selected YES');
}
else
{
alert('You selected NO');
}
}
|
The result variable will contain the Boolean value indicating that if yes was
selected or no was selected.
Then we are just popping a simple message box which informs the user that if
the YES was selected or NO was selected.
Now let's see the code behind file which attaches the event handler to the
button click control:
|
if(!Page.IsPostBack)
{
if(!Page.IsClientScriptBlockRegistered("MyScript"))
{
Page.RegisterClientScriptBlock("MyScript","<SCRIPT Language='JavaScript' src='MyJavaScriptFile.js'></SCRIPT>");
}
Button2.Attributes.Add("onclick","ConfirmationWindow();");
}
|
We have done this before in the previous examples so I don't think I need to
explain it again and again. It will be a better idea to load the script when you
are in the Initialize event handler or maybe you don't want to include a check
for the IsPostBack since you want the script to load every time the page is
loaded.
Here is a simple screen shot displaying the confirmation box:

And when you press the "ok" button it will display the following window:

So, in this article we saw how we can use the client script with the Asp.net
pages. I hope you enjoyed the Tutorial.
Happy Coding !
Attachments:
Project Files: ClientInteraction.zip