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" %>
<%----%>
<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>
<%----%>
<script type="text/javascript">
window["<%= Me.GreeterName %>"] = function () {
var messageId = "<%= divMessage.ClientID %>";
var messageElement = document.getElementById(messageId);
messageElement.style.display = "block";
};
</script>
<%----%>
<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>
<%----%>
<html>
<head>
<title>Greeter Test</title>
</head>
<body>
<%----%>
<div>
<a runat="server" id="aClicker" href="#">Click!</a>
</div>
<people:greeter runat="server" ID="doorman" />
<%----%>
<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).