Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple instances of an aspx user control in a aspx page

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

like image 321
Muthukumar Palaniappan Avatar asked Jan 12 '23 09:01

Muthukumar Palaniappan


1 Answers

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" />
like image 84
Muthukumar Avatar answered Jan 26 '23 09:01

Muthukumar