Add JavaScript programmatically using RegisterStartupScript during an Asynchronous postback

Posted by: Suprotim Agarwal , on 9/11/2008, in Category ASP.NET AJAX
Views: 173851
Abstract: The ClientScriptManager class contains various methods to add client scripts to a webpage using server side code. One of the methods you can use is the RegisterStartupScript() method of the ClientScriptManager class. However, this method does not work if the control used to register this method is wrapped inside an UpdatePanel. In this short article, we will explore how to add javascript programmatically using the ScriptManager.RegisterStartupScript, while performing an asynchronous postback.
Add JavaScript programmatically using RegisterStartupScript during an Asynchronous postback
 
The ClientScriptManager class contains various methods to add client scripts to a webpage using server side code. For example: you may need to add javascript programmatically to the page on a button click before posting back the page. One of the methods you can use is the  RegisterStartupScript() method of the ClientScriptManager class. However, this method does not work if the button control is wrapped inside an UpdatePanel. In this short article, we will explore how to add javascript programmatically using the ScriptManager.RegisterStartupScript, while performing an asynchronous postback. I also aim to cover some common mistakes developers make while using the ScriptManager class to add client scripts programmatically.
We will study two scenarios in this article:
The first one, where we will use the ClientScript.RegisterStartupScript() to add script dynamically on a button click. We will add a label displaying the time, as well as change the color of the label to make sure the postback occurred.
In the second scenario, we will add the button and label control inside an UpdatePanel. We will try and use the same code, which will not work. We will then see how to add javascript programmatically during an async postback.
Scenario 1:
Create an ASP.NET project. Now add a Label(lblDisplayDate) and a Button(btnPostback) control to the page.
On the Button click, register the following script dynamically using the ClientScriptManager.RegisterStartupScript to change the color of the label controls to Red.
C#
protected void Page_Load(object sender, EventArgs e)
{
    lblDisplayDate.Text = System.DateTime.Now.ToString("T");
}
 
protected void btnPostback_Click(object sender, EventArgs e)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append(@"<script language='javascript'>");
    sb.Append(@"var lbl = document.getElementById('lblDisplayDate');");
    sb.Append(@"lbl.style.color='red';");
    sb.Append(@"</script>");
 
    if (!ClientScript.IsStartupScriptRegistered("JSScript"))
    {
        ClientScript.RegisterStartupScript(this.GetType(), "JSScript", sb.ToString());
    }
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      lblDisplayDate.Text = System.DateTime.Now.ToString("T")
End Sub
 
Protected Sub btnPostback_Click(ByVal sender As Object, ByVal e As EventArgs)
      Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
      sb.Append("<script language='javascript'>")
      sb.Append("var lbl = document.getElementById('lblDisplayDate');")
      sb.Append("lbl.style.color='red';")
      sb.Append("</script>")
 
      If (Not ClientScript.IsStartupScriptRegistered("JSScript")) Then
            ClientScript.RegisterStartupScript(Me.GetType(), "JSScript", sb.ToString())
      End If
End Sub
When you run the application and click on the button, you will observe that the label is updated with a new time and the color of the label turns to red. This confirms that there was a postback, as well as the dynamically added JavaScript executed.
Scenario 2:
Now wrap the label and the button control inside an UpdatePanel as shown below:
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Label ID="lblDisplayDate" runat="server" Text="Label"></asp:Label>
         <asp:Button ID="btnPostback" runat="server" onclick="btnPostback_Click"
        Text="ClickMe" />
    </ContentTemplate>
</asp:UpdatePanel>
</div>
When you now run the application and click on the button, you will observe that the label is updated with the new time (which means the postback occurred), however the color of the label does not turn to red. This is because when using an Update Panel, the JavaScript that is dynamically added to the page using ClientScript.RegisterStartupScript() does not execute.
Solution:
Use the ScriptManager.RegisterStartupScript(). If you take a look at the methods of the ScriptManager class, you will observe that the methods to register client script to the page using the ClientScriptManager class, are also present in the ScriptManager class. So modify the code as shown below:
C#
protected void btnPostback_Click(object sender, EventArgs e)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append(@"<script language='javascript'>");
    sb.Append(@"var lbl = document.getElementById('lblDisplayDate');");
    sb.Append(@"lbl.style.color='red';");
    sb.Append(@"</script>");
 
    ScriptManager.RegisterStartupScript(btnPostback,this.GetType(), "JSCR", sb.ToString(),false);
 
}
VB.NET
Protected Sub btnPostback_Click(ByVal sender As Object, ByVal e As EventArgs)
      Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
      sb.Append("<script language='javascript'>")
      sb.Append("var lbl = document.getElementById('lblDisplayDate');")
      sb.Append("lbl.style.color='red';")
      sb.Append("</script>")
 
      ScriptManager.RegisterStartupScript(btnPostback,Me.GetType(), "JSCR", sb.ToString(),False)
 
End Sub
Note 1: Observe that the last parameter to RegisterStartupScript is set to 'false'. This prevents us from inserting the <script> tags automatically. Since we have already inserted the <script> tags while creating the script in the StringBuilder, we do not need to insert them now. Setting the last parameter to 'true' in such cases is a very common mistake developers do.
Note 2: Building up javascript using the StringBuilder as shown above is not advisable in large projects. Instead you should keep the javascript in a seperate .js file and refer the .js.
That’s it. Run the application and you will observe that that the label is updated with a new time and the color of the label turns to red, even while performing an asynchronous postback.
In this article, we explored how to use the ScriptManager.RegisterStartupScript method to add client script to a page when the control is wrapped inside an UpdatePanel. We also covered some common mistakes people make while using the ScriptManager class to add client scripts programmatically. I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed.

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Kapil on Thursday, September 18, 2008 5:41 AM
Good matter
Comment posted by praveena on Friday, September 26, 2008 3:03 AM
This article was very helpful to me. This is good and understandable
Comment posted by Itai on Sunday, September 28, 2008 4:56 AM
Great article, very helpful!! thanks!
Comment posted by Pawan kumar on Wednesday, October 1, 2008 8:38 AM
Nice article for all type of user.
http://dev.codeplatter.com
.Net discussion forum
Comment posted by Sam on Friday, October 3, 2008 4:35 PM
Perfect!  Just what I was looking for, thank you so much!
Comment posted by sasi on Monday, October 6, 2008 6:24 AM
Nice Article
Comment posted by NAB on Saturday, October 18, 2008 9:37 AM
Thanks a lot for the lovely article.

One thing though language is a deprecated attribute. It is better to use type instead.
Comment posted by hgfhgf on Friday, November 28, 2008 12:54 PM
ghfghgfh
Comment posted by tx on Sunday, December 14, 2008 2:09 PM
Thank you very much. Great article, exactly the solution for my problem.
Comment posted by Jerome on Thursday, December 18, 2008 6:14 AM
No this is not working for me. I am using VISTA Ultimate & VS 2005

My code is like this :

string sScript;
sScript = "<script language='javascript' type='text/javascript'>";
sScript += "alert('Welcome');";
sScript += "</script>";
           ScriptManager.RegisterStartupScript(this.page, typeof(this.Page), "JSCR", sScript, false);

Any Suggestions??
Comment posted by Jerome on Thursday, December 18, 2008 6:17 AM
No this is not working for me. I am using VISTA Ultimate & VS 2005

My code is like this :

string sScript;
sScript = "<script language='javascript' type='text/javascript'>";
sScript += "alert('Welcome');";
sScript += "</script>";
           ScriptManager.RegisterStartupScript(this.page, typeof(this.Page), "JSCR", sScript, false);

Any Suggestions??
Comment posted by Billy from Stanmore on Wednesday, April 1, 2009 4:14 AM
this article saved me from pulling my hair out. thank you for posting it.
Comment posted by Gautam Jain on Wednesday, May 20, 2009 9:42 AM
Thank you. Thank you very much. I spent several hours to find the fix. And you have it on this page.
Comment posted by Brandon on Wednesday, June 10, 2009 3:30 PM
The javascript to add a pane during pageLoad yeilded odd results in firefox 3.0.1; no text for either the header or content. It does work IE 8. Other than this firefox issue, this is great! Thank you.
Comment posted by Brandon on Wednesday, June 10, 2009 3:32 PM
Please disregard my last post; I posted to the incorrect page. My bad. Should have been the article on Accordion.
Comment posted by shashankkadge on Thursday, September 3, 2009 12:24 PM
I have used ScriptManager methods before. Is there a way to have a javascript confirm method to pop-up from the server side button click and depending the response execute the server side code.

thanks
Comment posted by Vijeth on Wednesday, May 26, 2010 7:54 AM
Amazing article... Saved a lot of time for calling Javascript from C#. Thanks a lot!!
Comment posted by KidJ77 on Thursday, June 24, 2010 4:59 PM
Good Article
Comment posted by Pravin Bhongale on Friday, July 23, 2010 2:28 AM
Fail to create javascript function using ScriptManager.RegisterStartupScript during an Asynchronous postback.
ScriptManager.RegisterClientScriptBlock(Me.Page, Me.Page.GetType, "asda", "function GetJavascript() { alert('fghf fghf'); }", True)
Comment posted by Ponkarthikeyan on Tuesday, December 21, 2010 10:18 PM
Easy to understand and is simple & clear.
Comment posted by CAV on Monday, January 31, 2011 5:52 PM
Wow, tanx dude. This was extremely helpful, you just helped em solve a week-long problem =P
Comment posted by Yamuna on Monday, March 28, 2011 1:25 PM
Thank you.I spent days on this issue.. and finally found your article, which was very helpful.
Comment posted by spice on Monday, May 16, 2011 3:51 AM
what if the script is boolean? confirm dialog box for example?
Comment posted by Indresh on Friday, May 27, 2011 2:26 AM
Tanks Dude its really helping. I spent whole day on it but could not resolve finally got your article it solved my problem.

Thanks Once again
Comment posted by Dom on Saturday, June 25, 2011 6:51 PM
is there any way of doing this but calling an entire .js file? Thanks x
Comment posted by Praveen Solaki on Monday, February 20, 2012 1:08 AM
Thanks its really simple and helpful...
Comment posted by June on Sunday, March 25, 2012 10:44 PM
Thanks
Comment posted by Eric on Wednesday, March 28, 2012 4:49 PM
how to I use the external js file intead of string build like you have in your example?  thank you
Comment posted by Mohamed eltigani on Wednesday, June 6, 2012 4:10 PM
nice, can you provide a sample for the case of using .js file?
Comment posted by Shubham on Thursday, June 28, 2012 12:52 AM
Thanx sir! its helping..  

But while i tried for the lable to be red (the 2nd code u've given) it gives me a runtime Jscript error.. please suggest.. Thank you..!
Comment posted by Meghna Godhani on Friday, August 24, 2012 12:25 AM
Really Good Araticle which can help developers a lot to understand the actual difference... thanks a lot Suprotim...
Comment posted by NS on Tuesday, September 18, 2012 6:41 AM
Really Good.. Examples..
it helps me alot..
Thanks..
Comment posted by Khaled Samir on Wednesday, September 26, 2012 6:46 PM
Thank you very very much , I have this problem in my project and will do this tomorrow and see what will happen. :)

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel