Posts Tagged ‘alert’

.Net ASP.Net – Calling JavaScript from Code Behind

0 Comments

.Net gives us the ability to call javascript code from the code behind. This means that you don’t have to write the javascript code in the “Source” of the aspx page.

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());
}

To run a method that is already defined in the .aspx page, you would use similar code, but with one difference:

// javascript method
<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);

And it’s that simple.

Tags: , , ,