Click here to Skip to main content
15,885,546 members
Articles / Web Development / ASP.NET
Tip/Trick

Call JavaScript in an ASP.NET User Control

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
20 May 2013CPOL1 min read 55K   6   3
Call a uniquely named JavaScript function inside of an ASP.NET user control from the page it is hosted inside of.

In ASP.NET it is easy to call a server-side function on a user control during postback. However, you have to do some custom code if you want to call a JavaScript function that resides inside of a user control without performing a postback.

Suppose you have a user control, Greeter, that shows a message to the user. Now, you'd like to initiate that greeting with some JavaScript that is outside of the Greeter control. For our example, we'll have the Default page call some JavaScript on the click event of an element in the page. That JavaScript will call a JavaScript function within the Greeter control. Here is the control, Greeter.ascx:

ASP.NET
<%@ Control Language="vb" %>

<%-- Server-side code. --%>
<script runat="server">
  Private _greeterName As String = Nothing

  Public ReadOnly Property GreeterName As String
    Get
      If _greeterName Is Nothing Then
        _greeterName = "Greeter_" + Guid.NewGuid.ToString("N")
      End If
      Return _greeterName
    End Get
  End Property
</script>

<%-- JavaScript. --%>
<script type="text/javascript">
  window["<%= Me.GreeterName %>"] = function () {
    var messageId = "<%= divMessage.ClientID %>";
    var messageElement = document.getElementById(messageId);
    messageElement.style.display = "block";
  };
</script>

<%-- Markup. --%>
<div runat="server" id="divMessage" style="display: none;">
  Hello
</div>

And here is the page, Default.aspx:

ASP.NET
<%@ Page Language="vb" %>
<%@ Register Src="~/Greeter.ascx" TagPrefix="people" 
          TagName="greeter" %><!DOCTYPE html>
<%-- The doctype is on the above line to prevent preceding whitespace,
     which some browsers dislike. --%>
<html>
  <head>
    <title>Greeter Test</title>
  </head>
  <body>

    <%-- Markup. --%>
    <div>
      <a runat="server" id="aClicker" href="#">Click!</a>
    </div>
    <people:greeter runat="server" ID="doorman" />

    <%-- JavaScript. --%>
    <script type="text/javascript">
      (function () {
        var clickerId = "<%= aClicker.ClientID %>";
        var clickerElement = document.getElementById(clickerId);
        clickerElement.onclick = function () {
          var fnName = "<%= doorman.GreeterName%>";
          var fnHandle = window[fnName];
          fnHandle();
          return false;
        };
      })();
    </script>

  </body>
</html>

The Greeter control contains a hidden div that contains the message "Hello." It also defines a function to show that hidden div. That function is given a random name at runtime, and is assigned to the global scope using the window variable. All that you need to do is figure out a way to call that function.

The default page gets the name of the function from a property on the Greeter control. From there, it gets the function from the window variable, then calls the function (when the anchor tag is clicked).

So, the user clicks an anchor tag, which calls a JavaScript function defined on the Default page. That JavaScript function then finds the name of the Greeter JavaScript function, and calls that function. Using this technique, you can more easily decouple your controls so that the markup can be more varied (i.e., the control doesn't have to know how its JavaScript gets called, it only needs to provide a means to do so).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States

  • Managing Your JavaScript Library in ASP.NET (if you work with ASP.net and you don't read that, you are dead to me).
  • Graduated summa cum laude with a BS in Computer Science.
  • Wrote some articles and some tips.
  • DDR ("New high score? What does that mean? Did I break it?"), ping pong, and volleyball enthusiast.
  • Software I have donated to (you should too):

Comments and Discussions

 
QuestionPostback Hides DIV again... Pin
Member 1114382531-Mar-15 5:41
Member 1114382531-Mar-15 5:41 
AnswerRe: Postback Hides DIV again... Pin
AspDotNetDev31-Mar-15 19:49
protectorAspDotNetDev31-Mar-15 19:49 
GeneralRe: Postback Hides DIV again... Pin
Member 111438251-Apr-15 7:34
Member 111438251-Apr-15 7:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.