4

I am facing a problem in using more than one instance of an aspx user control in a aspx page. This happens when I tried to fetch User control element value through Java script.

User Control Code:

<script type="text/javascript">
    function ucFun()
    {
        var a = document.getElementById("<%=tbName.ClientID%>");
        alert(a.value);
        return false;
    }
</script>
<asp:Label Text="Name" runat="server" ID="lblname"></asp:Label>
<asp:TextBox ID="tbName" runat="server" ></asp:TextBox>
<asp:Button ID="btSubmit" runat="server" Text="Go" OnClientClick="ucFun()" />

Web Form Code

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
            <uc:cont runat="server" ID="ucID" />
                <uc:cont runat="server" ID="Cont1" />
                <uc:cont runat="server" ID="Cont2" />
            </div>
        </form>
    </body>
</html>

on clicking the Go button, it displays null int he alert box, as the element is undefined. However, When I have one instance of User control in the form, it rightly displayed the text box value.

Is there any way we should write this..

Andrea
  • 11,801
  • 17
  • 65
  • 72
Muthukumar Palaniappan
  • 1,622
  • 5
  • 25
  • 49
  • 1
    As your function name doesn't changes, when you add the second control the first version of `ucFun` is overwritten. – Rubens Farias Jan 23 '14 at 09:09
  • Thanks Rubens for replying. If I need to validate UC fields,then I have to write JS on the UC fetching field values. Using Multiple instances of UC will fail then. How can we acheive it – Muthukumar Palaniappan Jan 23 '14 at 09:18

2 Answers2

10

After some searching found a different solution.

http://www.aspsnippets.com/Articles/Issue-JavaScript-in-WebUserControl-not-working-when-used-multiple-times-on-same-page.aspx

Here they append an uniqueID with the javascript name, thereby there is no conflict with the javascripts.

UserControl.CS

protected string uniqueKey;
protected void Page_Load(object sender, EventArgs e)
{
    this.uniqueKey = Guid.NewGuid().ToString("N");
    this.Button1.Attributes["onclick"] = "return DisplayMessage_" + uniqueKey + "();";
}

UserControl.aspx

<%@ 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" />
Muthukumar
  • 8,679
  • 17
  • 61
  • 86
  • this worked but when content page have postback this is not worked because uniqueKey is changed – hojjat.mi Oct 26 '17 at 05:33
  • This helped me a lot. Thanks. – Diane Sep 07 '18 at 16:36
  • Thank you for the tip, @Muthukumar. I got the same results using 'this.ClientID', the ClientID of the User Control instead of the uniqueKey that you suggested. After all, it is unique and already generated for you. – CAK2 Aug 07 '19 at 00:07
0

Refer to the similar question in the post

Javascript functions inside ASP.NET User Control

You need to use ClientScriptManager as shown in the example below

 <%@ Page Language="C#"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  public void Page_Load(Object sender, EventArgs e)
  {
    // Define the name and type of the client scripts on the page.
    String csname1 = "PopupScript";
    String csname2 = "ButtonClickScript";
    Type cstype = this.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the startup script is already registered.
    if (!cs.IsStartupScriptRegistered(cstype, csname1))
    {
      String cstext1 = "alert('Hello World');";
      cs.RegisterStartupScript(cstype, csname1, cstext1, true);
    }

    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
    {
      StringBuilder cstext2 = new StringBuilder();
      cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
      cstext2.Append("Form1.Message.value='Text from client script.'} </");
      cstext2.Append("script>");
      cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
    }
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ClientScriptManager Example</title>
  </head>
  <body>
     <form id="Form1"
         runat="server">
        <input type="text" id="Message" /> <input type="button" value="ClickMe" onclick="DoClick()" />
     </form>
  </body>
</html>
Community
  • 1
  • 1
Muthukumar
  • 8,679
  • 17
  • 61
  • 86
  • I understand that we can limit script registrations by Registering scripts from the server side. However, we could not fetch appropriate field values of the instance, as we just register one script for one instance. I mean displaying <%=tbName.ClientID%> return appropriate field's value of the user control instance. – Muthukumar Palaniappan Jan 23 '14 at 11:13
  • This does not address the issue specified in the question, it is a completely separate topic. – jtate Apr 28 '15 at 20:21