What is the Difference between RegisterStartupScript and RegisterClientScriptBlock?

 Posted by Lakhangarg on 10/29/2009 | Category: ASP.NET Interview questions | Views: 10078
Answer:

RegisterStartupScript Places the script at the bottom of the asp.net page instead of at the top. and RegisterClientScriptBlock inserts script immediately below the opening tag of the Page . means after <form> tag.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Poster on: 10/29/2009
Hey Lakhan,

Your answer seems incomplete.

What about RegisterClientScriptBlock, what it does?

Waiting for your reply. Kindly update your answer.

Thank you
Posted by: Virendradugar on: 10/30/2009
Here is my answer to this question:

The main difference is that the RegisterStartupScript method places the JavaScript at the bottom of the ASP.NET page right before the closing /form element. The RegisterClientScriptBlock method places the JavaScript directly after the opening <form> element in the page.

Both of these methods take two strings as input. The second parameter, script , is the client-side script-including the opening and closing script tags. The first parameter, key , serves as a unique identifier for the inserted client-side script.

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.

As for example if you have declared a hidden variable and want to use in your java script by any of these method then java script method registred with RegisterClientScriptBlock method won?t be able to find the hidden variable as the form elements are not instantiated yet.

Reference :http://virendradugar.wordpress.com/2009/02/13/difference-between-registerclientscript-registerstartupscript/

Thanks,
Virendra Dugar

Login to post response