Click here to Skip to main content
Click here to Skip to main content

Tagged as

Call JavaScript in an ASP.NET User Control

, 20 May 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

<%@ 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:

<%@ 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)

Share

About the Author

AspDotNetDev
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

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.141022.2 | Last Updated 20 May 2013
Article Copyright 2013 by AspDotNetDev
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid