ASP.NET Web Forms - How to refer to a client-side control encapsulated in a specific instance of UserControl
This example shows how to refer to a client-side control (pop-up window) encapsulated in a specific instance of a user control.
In this example, a user control contains ASPxButton and ASPxPopupControl components.
<dx:ASPxButton ID="btnShow" runat="server" AutoPostBack="false" Text="Open My Own PopupControl" OnInit="btnShow_Init" />
<dx:ASPxPopupControl ID="ASPxPopupControl1" runat="server" AllowDragging="True" CloseAction="CloseButton" OnInit="ASPxPopupControl1_Init" />
When a user clicks the button, the pop-up window appears. The common practice is to set the ClientInstanceName property of the ASPxPopupControl and use it for calling client-side methods:
<dx:ASPxPopupControl ID="ASPxPopupControl1" runat="server" ClientInstanceName="popupControl" ... />
popupControl.Show();
However, if you add multiple instances of the same user control to your page, the ClientInstanceName
is no longer unique, and both user control instances now open the first popup control. There are two solutions to resolve this issue:
- Dynamically generate client-side code and use the
ClientID
property. It's also necessary to set theEnableClientSideAPI
property totrue
and clear theClientInstanceName
property. - Dynamically generate a unique value for the
ClientInstanceName
property and also dynamically generate client-side code that uses the correctClientInstanceName
value.
This example uses the second approach to access the ASPxPopupControl on the client. The ClientInstanceName
property value for ASPxPopupControl and the Click
event handler for ASPxButton are generated dynamically.
protected void ASPxPopupControl1_Init(object sender, EventArgs e) {
ASPxPopupControl popupControl = (ASPxPopupControl)sender;
popupControl.ClientInstanceName = GetUserControlSpecificId("_popup");
popupControl.HeaderText = this.ID + "'s popup";
}
protected void btnShow_Init(object sender, EventArgs e) {
ASPxButton button = (ASPxButton)sender;
System.Threading.Thread.Sleep(50);
Random randomizer = new Random();
string clickEventCode = string.Format("function(s, e) { {0}.ShowAtPos({1}, {1}); }",
GetUserControlSpecificId("_popup"), 100 + randomizer.Next(DateTime.Now.Millisecond));
button.ClientSideEvents.Click = clickEventCode;
}
- Default.aspx (VB: Default.aspx)
- WebUserControl.ascx (VB: WebUserControl.ascx)
- WebUserControl.ascx.cs (VB: WebUserControl.ascx.vb)
(you will be redirected to DevExpress.com to submit your response)