Question

I have a user control(.ascx), which I am embedding in my page(.aspx), as below:

<%@ Register TagName="UI" TagPrefix="my" Src="~/userControls/UI.ascx" %> 
<my:UI runat="server" ID="mytestui" />

When page is loaded the controls(textboxes, dropdowns etc), inside the user control, changes automatically. Say I have a textbox called txtTest it changes to mytestui_txtTest.

As you can see it takes the ID of user control above and appends it to control.

Is there any way to prevent this from happening?

Was it helpful?

Solution

This happens because your control is a subclass of UserControl class, which implements INamingContainer interface. By default all controls that implement this interface prepend children's IDs with their own IDs, thus insuring that every ID on the page is unique.

To aviod this behavior you have two options:

  1. Create server control, inheriting not from UserControl but from Control class directly. This one does not implement INamingContainer. However you won't have markup file, and have to generate all controls programmatically.

  2. [Edit: ASP.NET 4 only] Use ClientIDMode="Static" for child controls. This mode insures that server and client IDs of the control are exactly the same. In this case this is a job of a developer to make sure that this control is used only once on the page to avoid ID duplicates.

OTHER TIPS

What version of .Net are you using? If >= 4.0 you can use ClientIDMode="Static" as Andrei said. You can set it at control or page level as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top