Wednesday 4 April 2012

RegisterClientScriptBlock and RegisterStartupScript

I will try to explain the difference between RegisterClientScriptBlock and RegisterStartupScript . I have experienced the difference while I was doing some stuffs yesterday. Here is what I was doing. I had a hidden field called txtHiddenField, an update button and some tabs in my page. I also have a javascript function called DisplayTab.

function DisplayTab(tabId)
{
var hdnView = document.getElementById("My hidden field's dotnet generated Id);
hdnView.value = tabId;
document.forms(0).submit();
}
When I click on those tabs I am calling the DisplayTab function with a tabid. It will work fine. ie there will not be any problem in finding the Hidden field using document.getElementById("My hidden field's dotnet generated Id);.

In my Update button click i have

ClientScript. RegisterClientScriptBlock (this.GetType(), "script", "<script language='javascript'> DisplayTab(0); </script>");
This time when it reaches the DisplayTab , it wont be able to find the hidden field . The hdnView variable will be having null. Change the RegisterClientScriptBlock to RegisterStartupScript. This time it works fine. How is this possible? There is only a slight difference between the two methods.

The RegisterClientScriptBlock method inserts the client-side script immediately below the opening tag of the Page object's <form runat="server"> element. The code cannot access any of the form's elements because, at that time, the elements haven't been instantiated yet. This explains why hdnView variable had a null value in my case. The RegisterStartupScript method inserts the specified client-side script just before the closing tag of the Page object's <form runat="server"> element. The code can access any of the form's elements because, at that time, the elements have been instantiated. The choice of which method to use really depends on the "order" in which you want your script to be run by the browser when rendering the page.

For Reference...... 

No comments:

Post a Comment