Wednesday, October 19, 2011

Register Client-Scripts Carefully

While working on AJAX or Javascript based applications it’s most likely that you will come across situation when you want to pass some information from server side to client side. And we all know that ScriptManager.RegisterStartupScript method is used to emit client side script to the page response. If you want to update any client side variables or call any client side methods from code behind we use this method.

Syntax for the function is as follows.

public static void RegisterStartupScript(

Page page,Type type,string key, string script,bool adddScriptTags

)

Simple enough right, now take one simple example

string strScriptBlock = "alert(‘This is Test’);";

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "TestKey”, strScriptBlock, true);

When executed, above script block will be added to the page and an alert will be shown.

Now let’s play with this

for (int i = 0; i < 3; i++)

{

string strScriptBlock = "alert(‘This is Test’);";

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "TestKey”, strScriptBlock, true);

}

What do you think will be the output for above code snippet? I know most of you might be thinking output as 3 javascript alerts. Buts that’s not correct. To my surprise initially I got only one alert box. I was wondering why this is so. Then I got into meat of this and found something interesting.

The key thing here is “key”. A client script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates. And when the server side processing is completed it will only include original copy of the client script block and ignores other duplicates.

In our example above we have mentioned key "TestKey”, so while iterating through for loop even though 3 client scripts are registered there is only one unique script key. Thus at the end only one client script block is attached with the page response and other 2 are ignored. Most of developers don’t think much about giving proper key name, but it’s important to know its significance.

Below is code indicating how we can avoid such situation.

for (int i = 0; i < 3; i++)

{

string strScriptBlock = "alert(‘This is Test’);";

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "TestKey”+i.ToString(), strScriptBlock, true);

}

In here, I am giving key name dynamically by appending the indexer with the key name and it’s guaranteed to be different for each iteration of for loop. Thus three different client scripts will be registered with different keys. And in the output you will see 3 alert boxes. I recommend to try this out yourself to see how exactly things are happening.

Above concept equally applies to other client script registering methods such as Page.RegisterStartupScript or ClientScript.RegisterClientScriptBlock.

Hope you find this post useful, comments and feedbacks are welcome.

No comments:

Post a Comment