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
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>

If you want to learn more about how this can be done, read the rest of the post here: http://www.codeproject.com/Tips/595712/Call-JavaScript-in-an-ASP-NET-User-Control

Leave a Reply

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