Introduction
Registering Client script from server itself useful when , you want certain java script to be executed when page finished loading or when user does a submit on the form .
Background
To get the complete idea about the clientside java script registration from server , u go through the URL http://msdn2.microsoft.com/en-us/library/ms178207.aspx
Using the code
You have a clientscriptmanager object on each aspx page you have . the object name is ClientScript , using ClientScript you can register the script in 4 modes
1. RegisterClientScriptBlock:-Adds Script to the top of the page
2.RegisterClientScriptInclude:- Refer to a external .js file
3.RegisterStartupScript:- script is registered before onload event of a page
4. RegisterOnSubmitStatement:- Script is registered on onSubmit event of page
Have a look at the following example below which uses startupscript in my project, I used this one because I needed script to be executed and load a activex object before page is loaded.
if (!ClientScript.IsClientScriptBlockRegistered("exampleScript"))
ClientScript.RegisterStartupScript(this.GetType(), "exampleScript","
<script language = "'javascript'">
alert('you just registered the start up script')
</script>
");
public static void ConfirmMessageBox(ref System.Web.UI.WebControls.WebControl webControl, string message, string webControlName, string eventName)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("var str = trim(document.forms[0].{0}.value);", webControlName);
sb.Append("if(str != null)");
sb.Append("{");
sb.Append("if(str != '')");
sb.Append("{");
sb.AppendFormat("var bRet = confirm('{0}');", message);
sb.Append("if(!bRet)");
sb.AppendFormat("document.forms[0].{0}.value = '';", webControlName);
sb.Append("return bRet;");
sb.Append("}");
sb.Append("}");
webControl.Attributes.Add(eventName, sb.ToString());
}
WebControl control = (WebControl)textBoxControl;
ConfirmMessageBox(ref control, "Are you sure , you want to create this domain",
textBoxControl.ClientID, "onblur");