Adding client script to an ASP.NET Web page dynamically
RegisterClientScriptBlock
Adds a script block to the top of the page. You create the script as a string, and then pass it to the method, which adds it to the page. You can use this method to insert any script into the page. Note that the script might be rendered into the page before all the elements are finished; therefore, you might not be able to reference all the elements on the page from the script.
Example
void Page_Load(object sender, EventArgs e)
{
Page.RegisterClientScriptBlock("MyScript", "<script language=javascript>" + "if (document.images) {" + "MyButton = new Image;" + "MyButtonShaded = new Image;" + "MyButton.src = 'button1.jpg';" + "MyButtonShaded.src = 'button2.jpg';" + "}" + "else {" + "MyButton = '';" + "MyButtonShaded = '';" + "}" + "</script>"); ImageButton1.Attributes.Add("onmouseover", "this.src = MyButtonShaded.src;" + "window.status='Oh Yes! Click here!';"); ImageButton1.Attributes.Add("onmouseout", "this.src = MyButton.src;" + "window.status='';");
}
RegisterClientScriptInclude
Similar to the RegisterClientScriptBlock method, but adds a script block that references an external .js file. The include file is added before any other dynamically added script; therefore, you might not be able to reference some elements on the page.
Example
Page.ClientScript.RegisterClientScriptInclude("my" ,
ResolveClientUrl("~/scripts/timer.js"));
RegisterStartupScript
Adds a script block into the page that executes when the page finishes loading but before the page's onload event is raised. The script is typically not created as an event handler or function; it generally includes only the statements you want to execute once.
Example
private void Page_Load(object sender, System.EventArgs e)
{
string jScriptValidator; jScriptValidator="<script> function ReqFieldValidator()" + " { if (document.forms[0].txtField.value == '') \n"; jScriptValidator+="{ alert('TextBox cannot be empty') \n "; jScriptValidator+="return false; \n"; jScriptValidator+="} \n"; jScriptValidator+=" return true \n"; jScriptValidator+=" } </script>"; Page.RegisterStartupScript("regJSval",jScriptValidator); btnSubmit.Attributes.Add("onclick","return ReqFieldValidator()");
}
RegisterOnSubmitStatement
Adds script that executes in response to the page's onsubmit event. The script is executed before the page is submitted, and gives you an opportunity to cancel the submission.
0 comments