How to Call JavaScript in ASP.NET User Controls

In ASP.NET you can call server-side function on a user control. However, if you want to do some custom code if you want to call a JavaScript function that sits inside user control without performing a postback.

For example, you have a user control, Greeter which displays the message to the user. Now you’ll want to initiate the greting with some JavaScript outside the Greeter control.

Here’s the code for Greeter.ascx:
<%@ Control Language=”vb” %>

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

Public ReadOnly Property GreeterName As String
If _greeterName Is Nothing Then
_greeterName = “Greeter_” + Guid.NewGuid.ToString(“N”)
End If
Return _greeterName
End Get
End Property

<%– JavaScript. –%>
<script type=”text/javascript”>
window[“<%= Me.GreeterName %>”] = function () {
var messageId = “<%= divMessage.ClientID %>”;
var messageElement = document.getElementById(messageId); = “block”;

<%– Markup. –%>
<div runat=”server” id=”divMessage” style=”display: none;”>

If you want to learn more about how this can be done, read the rest of the post here:

Leave a Reply

Your email address will not be published. Required fields are marked *