This is a mirror of official site: http://jasper-net.blogspot.com/

ASP.Net – Calling JavaScript from Code Behind

| Monday, August 16, 2010
.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());
}

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


Read more: </dream-in-code>

Posted via email from .NET Info

0 comments: