Executing JavaScript function from server-side code

Tuesday, May 05, 2009 by Support Dept | Comments 10

This is a pretty common scenario when working with WebForms. There are many ways to achieve the desired result, but they have one thing in common – you should make sure that the controls are fully loaded in the page before trying to get a reference to them and use them in your JavaScript code.

In ASP.NET it is pretty straightforward to do that. For example you could use a label:
ASPX
<head runat="server">
   
<title>Untitled Page</title>
   
<script type="text/javascript">
   
function calledFn()
   
{
       
alert("code fired"); 
   
}
   
</script>
</head>
<body>
   
<form id="form1" runat="server">
       
<asp:Button ID="Button1" runat="server" Text="Run JavaScript Code" OnClick="Button1_Click" />
        <
asp:Label ID="Label1" runat="server"></asp:Label>
   
</form>

 

C#
protected void Button1_Click(object sender, EventArgs e)
{
   
Label1.Text = "<script type='text/javascript'>calledFn()</script>";
}

VB.NET
Protected Sub Button1_Click(sender As Object, e As EventArgs)
   
Label1.Text = "<script type='text/javascript'>calledFn()</script>"
End Sub

As an alternative, you could use Literal, Page.RegisterStartupScript, Page.RegisterClientScriptBlock or if you are using ASP.NET 2.x - ClientScriptManager.RegisterStartupScriptClientScriptManager.RegisterClientScriptBlock methods.

Note: The main difference between RegisterClientScriptBlock and RegisterStartupScript methods is that RegisterClientScriptBlock places the JavaScript directly after the opening <form> element in the page while RegisterStartupScript inserts the code at the end of the page, right before the closing </form> tag.

 

In ASP.NET AJAX environment however, you should take into consideration the fact that the ASP.NET AJAX controls are loaded after window.onload is fired. You can verify this by putting some ASP.NET AJAX controls (I would personally recommend using RadControls for ASP.NET AJAX ;) ) and then examine the HTML of the rendered page.

Again, there are several ways to ensure that the controls are loaded on the client before trying to use them. If you want to use the RegisterStartupScript() method, I would recommend to check the ASP.NET AJAX’s Sys.Application.Load event. This event is raised after all scripts have been loaded on the page and the controls have been created and initialized. You need to make sure however, that the code that you will insert in the Load event will be executed only once and then removed, otherwise it will be called after every Ajax callback. For example you could use the following logic:
function f() 
{ 
   
//code
    Sys.Application.remove_load(f); 
} 
Sys.Application.add_load(f); 

 

For example let’s call the RadWindow’s radalert() function after a postback by using the code above

ASPX:
<form id="form1" runat="server"> 
   
<asp:ScriptManager ID="ScriptManager1" runat="server" />
    <
telerik:RadWindowManager ID="RadWindowManager1" runat="server"> 
   
</telerik:RadWindowManager> 
   
<asp:Button ID="Button1" Text="Postback and show RadAlert" runat="server"  OnClick="Button1_Click" />
</
form>

C#
protected void Button1_Click(object sender, EventArgs e) 
{ 
   
string radalertscript = "<script language='javascript'>function f(){radalert('Welcome to RadWindow for <strong>ASP.NET AJAX</strong>!', 330, 210); Sys.Application.remove_load(f);}; Sys.Application.add_load(f);</script>"; 
   
Page.ClientScript.RegisterStartupScript(this.GetType(), "radalert", radalertscript); 
} 

 

VB.NET
Protected Sub Button1_Click(sender As Object, e As EventArgs) 
   
Dim radalertscript As String = "<script language='javascript'>function f(){radalert('Welcome to RadWindow <strong>ASP.NET AJAX</strong>!', 330, 210); Sys.Application.remove_load(f);}; Sys.Application.add_load(f);</script>"
   
Page.ClientScript.RegisterStartupScript(Me.[GetType](), "radalert", radalertscript) 
End Sub 

 

If you are working with Ajax callbacks however, I would suggest to use asp:Scriptmanager’s RegisterStartupScript() method.

 

ASPX
<form id="form1" runat="server"> 
   
<asp:ScriptManager ID="ScriptManager1" runat="server"> 
   
</asp:ScriptManager> 
   
<telerik:RadWindowManager ID="RadWindowManager1" runat="server"> 
   
</telerik:RadWindowManager> 
   
<asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
       
<ContentTemplate> 
           
<asp:Button ID="Button1" Text="CallBack and show RadAlert" runat="server" OnClick="Button1_Click" />
        </
ContentTemplate> 
   
</asp:UpdatePanel> 
</form>

C#
protected void Button1_Click(object sender, EventArgs e) 
{ 
   
string scriptstring = "radalert('Welcome to Rad<strong>Window</strong>!', 330, 210);"; 
   
ScriptManager.RegisterStartupScript(this, this.GetType(), "radalert", scriptstring, true); 
}

VB.NET
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
   
Dim scriptstring As String = "radalert('Welcome to Rad<strong>Window</strong>!', 330, 210);"
   
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "radalert", scriptstring, True) 
End Sub 

More information on this subject can also be found in these KB articles (they are about RadWindow but use general approaches that can be applied to different scenarios:

And in the following MSDN article: Using JavaScript Along with ASP.NET 2.0 (by Bill Evjen)

 

In conclusion: Calling JavaScript function from server is a relatively easy task. Just make sure that:

  1. The code is actually inserted on the page – the easiest way is to put a simple alert() and check if it is fired.
  2. The controls are rendered on the page before referencing them in your JavaScript function
  3. If you are manually inserting the <script> tags – that you have set either the type (type=’text/javascript’) or the language (language=’javascript’) attributes.

 

Georgi Tunev
Telerik

10 Comments

  • nsn 27 Apr
    how to disable radwindow close,minimize buttons
  • Georgi Tunev 28 Apr
    You should use the Behaviors property - just set the behaviors that you want to allow for the object.
    For example:
    Behaviors="Move, Resize, Pin"
  • Mikey 30 Sep
    If you want to run a script at startup, why not just call:
        RadAjaxManager.ResponseScripts.Add("alert('hello world');");
    etc?

    Sorry, but I'm missing what is added by loading script text into a label or literal over the proper method... also, loading the script text into a label or a literal doesn't appear to even work if your control wasn't visible during the first physical load.  (ex: if during an ajax post back the control becomes visible, code tags inside of its labels does not appear to be executed).

  • Georgi Tunev 01 Oct
    Hi Mikey,

    Yes, RadAjaxManager's ResponseScripts collection can be used too, although for this purpose you need to have the manager on the page, which is not always the case.
    Basically, this blog was written some time ago to help customers output radalert() / radconfirm() / radprompt() / radopen() functions from the server and that is why the blog is more specific about these cases where you must make sure that the code will be executed only after all ASP.NET AJAX controls (including ours) are rendered and operational on the page. As for loading the script into a literal or label, I just gave these as an example how this was possible in ASP.NET. I noted however, that these methods will not work (they will work in specific cases only) whenever Ajax (controls) are involved.
  • TriSys 04 Nov
    Tested the above approaches in VS2010 with latest Telerik tools against IE8 and get the 'javascript object' errors - can you please retest your code?
  • trisys 04 Nov
    Turns out that this is essential:

    <

     

     

    telerik:RadWindowManager ID="RadWindowManager1" runat="server">

     

     

     

    </telerik:RadWindowManager>

    Working now - thanks.

     

  • Everton 19 Nov
    thank you, very useful!
  • David 28 Dec
    This was extremely helpful.  I had checked my code 50 times and couldn't figure out why my javascript couldn't find the RadWindowManager.  Now it works perfectly.
  • David 25 Feb
    Thanks for sharing. Finally found this after reading through many posts - so it looks like there are still a lot of frustrated developers out there.
  • Praveen 09 Mar
    Label1.Text = "<script type='text/javascript'>calledFn()</script>"; 

    Thanks helped me alot !!!

Add comment

  1. Formatting options
       
     
     
     
     
       
  2. (optional, emails won't be shown on public pages)
  3. (optional)