The difference between Response.Write and Page.ClientScript.RegisterStartupScript and Page.ClientScript.RegisterClientScriptBlock
Method 1, using Response.Write, this method will write the JS code at the top of the page (System.Web.HttpContext.Current.Response.Write ("<script Language=javascript>alert (JS code);</script>");
Method 2, using RegisterStartupScript, this method will embed the JS code at the bottom of the page, the end of the form (</form>), for the JS code to run after the page control is loaded:
System.Web.UI.Page Page = (System.Web.UI.Page) System.Web.HttpContext.Current.Handler;
if (!page. Clientscript.isstartupscriptregistered (page. GetType (), "ClientScript"))
Page. Clientscript.registerstartupscript (page. GetType (), "ClientScript", "<script Language=javascript>alert (JS code);</script>");
Method 3, using RegisterClientScriptBlock, this method will embed the JS code at the top of the page, the first (<form>) of the form, for the JS code to execute before the control is loaded, Similar to the Response.Write method above:
System.Web.UI.Page Page = (System.Web.UI.Page) System.Web.HttpContext.Current.Handler;
if (!page. Clientscript.isclientscriptblockregistered (page. GetType (), "ClientScript"))
Page. Clientscript.registerclientscriptblock (page. GetType (), "ClientScript", "<script Language=javascript>alert (JS code);</script>");
So what is the difference between method 2 and Method 3? The main difference is that the RegisterStartupScript method is to embed JavaScript at the bottom of an ASP. NET page, just before the close element </form>. The RegisterClientScriptBlock method is to embed JavaScript in the page to open the element <form> close behind. So, what's the difference? As we are going to see, this is a big difference.
In this example, here's how to place focus on a text box on a page when the page is loaded into the browser-using Visual Basic that leverages the RegisterStartupScript method:
Page.ClientScript.RegisterStartupScript (Me.GetType (), "testing", _ "Document.forms[0][textbox1].focus ();", True) This method works fine because the text box on the page has been generated and placed on the page when the browser runs to the bottom of the page and executes this little piece of JavaScript. However, if you do not follow the above method, write the following code (using the RegisterClientScriptBlock method):
Page.ClientScript.RegisterClientScriptBlock (Me.GetType (), "testing", _ "Document.forms[0][textbox1].focus ();", True) The TextBox control will not get focus and will generate a JavaScript error on the page