Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Response.Write() and ClientScript.RegisterStartupScript()?

Tags:

c#

asp.net

What is the difference between Response.Write() and ClientScript.RegisterStartupScript() Thank you.

like image 562
Surya sasidhar Avatar asked Dec 18 '09 05:12

Surya sasidhar


Video Answer


1 Answers

The Response.Write method can be used to output code during the rendering phase of the page. The <%= %> server tag is a shortcut for <%Response.Write( )%>.

If you use Response.Write from the code behind, you will write to the page before it has started rendering, so the code will end up outside the html document. Eventhough the browser will execute the code, it doesn't work properly. Having something before the doctype tag will make the browser ignore the doctype and render the page in quirks mode, which usually breaks the layout. Also, as the script runs before anything of the page exists, the code can't access any elements in the page.

The ClientScript.RegisterStartupScript method is the preferred way of adding script dynamically to the page. It will render the script at the end of the form so that it doesn't break the html documnet, and it can access the elements in the form.

Also, you give each script an identity, which means that duplicates are removed. If a user control registers a script, and you use several instances of the user control, the script will only be rendered once in the page.

like image 54
Guffa Avatar answered Sep 30 '22 17:09

Guffa