Just for an example, let’s say that you have a button on a form that just want to popup an alert that says “HEY” when it is clicked.
protected void btnHey_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); sb.Append("<script language='javascript'>alert('HEY');</script>"); // if the script is not already registered if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "HeyPopup")) ClientScript.RegisterClientScriptBlock(Page.GetType(), "HeyPopup", sb.ToString()); }
Let's say that there is already a javascript method in the ASPX page. To run that method, you would use similar code, but with one difference:
// javascript method in ASPX page <script language="javascript" type="text/javascript"> function ShowMessage(myMessage){ alert(myMessage); } </script> // C# code protected void btnHey_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); sb.Append("ShowMessage('hey');"); // if the script is not already registered if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "HeyPopup")) // notice that I added the boolean value as the last parameter ClientScript.RegisterClientScriptBlock(Page.GetType(), "HeyPopup", sb.ToString(), true);