How To Call/Inject JavaScript From CodeBehind ASP.NET

I had an issue where I was dealing with an Infragistics control (WebSpellChecker) that is only available to be triggered via clientside JavaScript. I wanted to do some server side validation before the JavaScript code to launch the WebSpellChecker dialog.

I was able todo this easily by first adding an UpdatePanel to the Page:

Example 1


        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:ImageButton ID="btnSpellCheck" runat="server" Visible="false" CssClass="img" AlternateText="SpellCheck this Page" ImageUrl="~/Images/icons/spellcheck.gif" ToolTip="SpellCheck this Page"/>
            </ContentTemplate>
        </asp:UpdatePanel>

<asp:UpdatePanel ID="UpdatePanelSpellCheck" runat="server">    
</asp:UpdatePanel>

From the code behind I validate first and if all is successful I use the ScriptManager.RegisterClientScriptBlock method pointing it to the instance of the update panel, pass it a unique key (I’m cheating by using the ClientID but if I wanted multiple scripts I could generate multiple keys) and then the JavaScript you want, and it will be executed once the update panel is done rendering.


        /// <summary>
        /// Handles the Click event of the SpellCheckButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
        void SpellCheckButton_Click(object sender, ImageClickEventArgs e)
        {

             // Does the user have unsaved comments?
            if (ctrlReviewJHACtrl.CtrlReviewCommentsListIntro.HasUnsavedChanges)
            {
                ((EHAP_MasterPage)Master).ErrorMessage = "Unsaved changes to summary comments.  Please either save or remove these comments.";
                return;
            }
            else if (ctrlReviewJHACtrl.ValidateComments)
            {
                ((EHAP_MasterPage)Master).ErrorMessage = "Unsaved changes to job step comments.  Please either save or remove these comments.";
                return;
            }
            else
            {
                // Otherwise present Spell Checker
                string spellCheckScript = string.Format(@"<script language='javascript'>o" + this.webSpellChecker.ClientID + ".checkTextComponent();</script>");
                ScriptManager.RegisterClientScriptBlock(UpdatePanelSpellCheck, typeof(UpdatePanel), UpdatePanelSpellCheck.ClientID, "o" + this.webSpellChecker.ClientID + ".checkTextComponent();", true);
            }  
            
        }

Another simpler example that just presents a JavaScript alert box:

Example 2

<asp:UpdatePanel ID="updPanel" UpdateMode="Conditional" runat="server">
   <Triggers>
      <asp:AsyncPostBackTrigger ControlID="btnClick" EventName="Click" />
   </Triggers>
   <ContentTemplate>
       <asp:ImageButton 
          ID="btnClick" 
          ImageUrl="button.png" 
          runat="server"
          CausesValidation="false" 
          OnClick="btnClick_Click"
          ToolTip="Click Me" 
          AlternateText="No, seriously, click me!" />
   </ContentTemplate>
</asp:UpdatePanel>

I wanted to dynamically inject some JavaScript. It’s a simple matter of registering the script. What threw me off is that you don’t use the current Page or event current ScriptManager, you call the static method on the class. It looks like this:

protected void btnClick_Click(object sender, ImageClickEventArgs e)
{
   btnClick.Text = "I was clicked."
   btnClick.Disabled = true;
   ScriptManager.RegisterClientScriptBlock(updPanel, typeof(UpdatePanel),updPanel.ClientID, "alert('wow!');",true);            
}

That’s it! Use the class, point it to the instance of your update panel, pass it a unique key (I’m cheating by using the ClientID but if I wanted multiple scripts I could generate multiple keys) and then the JavaScript you want, and it will be executed once the update panel is done rendering.

Source of Information

EDIT: Make sure that the button triggering the server-side event is wrapped in an UpdatePanel. In the first example I have two separate update panels. A more efficient way to do this would be to have just 1 like in example 2.

Advertisements

One thought on “How To Call/Inject JavaScript From CodeBehind ASP.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s