Issue: JavaScript in WebUserControl not working when used multiple times on same page
 
Author:
Filed Under: ASP.Net  |  JavaScript
Published Date: Jul 30, 2010
Views: 2886
 

Abstract: Here Mudassar Ahmed Khan has explained how to fix the issue of repetition of JavaScript code when a WebUserControls is used multiple times on a same page. This repetition causes the JavaScript methods to stop working. This article explains how to resolve this issue.

Comments:  1

 

In this article I’ll discuss an issue which is not discussed on many places but is an issue any one can face when he uses Web User Control and JavaScript combination in ASP.Net.
Issue
Consider a simple WebUserControl with some JavaScript below.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UC_TestCS.ascx.cs" Inherits="UC_TestCS" %>
<script type ="text/javascript">
function DisplayMessage() {
    var message = document.getElementById("<%=TextBox1.ClientID %>").value;
    alert(message);
    return false;
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Show Message"
OnClientClick = "return DisplayMessage();" />

The above WebUserControl simply runs a JavaScript method that displays the text from the TextBox in alert when the button is clicked.
Now I want to use the same WebUserControl on a page multiple times, hence I registered it and placed on the page twice with different Id which is normal and should not affect as WebUserControls are meant for reusability
<%@ Register Src = "~/UC_TestCS.ascx" TagName = "Test" TagPrefix = "uc" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <uc:Test ID = "ucTest1" runat = "server" /><br />
    <uc:Test ID = "ucTest2" runat = "server" />
    </div>
    </form>
</body>
</html>

Now the issue is that when I use the same WebUserControl multiple times on the same page it actually repeats itself. The Ids of the Controls are managed by .Net but the JavaScript is simply duplicated as shown in the screenshot below.
JavaScript Function and variables/objects Gets Duplicated When UserControls Used
In the above screenshot you can clearly see that the JavaScript functions are simply repeated. Hence when I try to run it and click the Button the second function is executed always irrespective of which button is clicked. Many will say to put JavaScript in JS Files but there we can’t make use of ClientID method.
Solution
The solution is that we should append a unique key or number to the method name so that each user control renders its JavaScript methods and variables with a unique name.
C#
protected string uniqueKey;
protected void Page_Load(object sender, EventArgs e)
{
    this.uniqueKey = Guid.NewGuid().ToString("N");
    this.Button1.Attributes["onclick"] = "return DisplayMessage_" + uniqueKey + "();";
}
 
VB.Net
Protected uniqueKey As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Me.uniqueKey = Guid.NewGuid.ToString("N")
        Me.Button1.Attributes("onclick") = ("return DisplayMessage_" _
                    + (uniqueKey + "();"))
End Sub

The above code snippet generates a unique key and assigns it to the protected variable. Now I can use this variable to append the unique key to the method and variable names in JavaScript. Also you will see that instead if OnClientClick event I am now assigning the JavaScript setting it server side so that the unique key can be appended to the method call.
Below is markup of the WebUserControl
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UC_TestCS.ascx.cs" Inherits="UC_TestCS" %>
<script type ="text/javascript">
function DisplayMessage_<%=uniqueKey %>() {
    var message = document.getElementById("<%=TextBox1.ClientID %>").value;
    alert(message);
    return false;
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Show Message" />

Above marked in GREEN you can see that I am appending the unique to the method name. This way even if I have multiple WebUserControls on the same web page the JavaScript methods will function properly as all will have unique names. The below screenshot displays the unique method names
JavaScript Methods functions Gets Duplicated When WebUserControl is Used multiple times on same page.png
With this we come to the end of this article. You can download the sample source code in VB.Net and C# using the link below.
Issue-JavascriptFunctionsDuplicatedinUsercontrols.zip
 








Related Articles



Comments



Add comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.

Name*: Required
Email*: Required
Comment*: Required
Security code*: CaptchaInvalid Security Code
  Submit