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

后端 未结 4 943
悲&欢浪女
悲&欢浪女 2020-12-17 05:52

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

4条回答
  •  半阙折子戏
    2020-12-17 06:26

    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.

提交回复
热议问题