asp.netwebforms

ASP.NET: A label's for="..." associated with input's ID in a user control don't match


I have a following set up:

<asp:Label Text="User Name" AssociatedControlID="inputUserName" runat="server">
<uc1:UserName ID="inputUserName" runat="server" />

And below is the UserName control:

<cc1:QPanel ID="pnlEdit" runat="server" Wrap="False">

After the page loaded, I inspect and see the input's id is generated by adding "_pnlEdit" at the end:

<label for="inputUserName">User Name</label>
<input id="inputUserName_pnlEdit">

So that the label's for and input's id don't match!

I thought the input's ID was generated after the AssociatedControlID took place in the label, so I try to reorder like below, but it doesn't work, either.

<uc1:UserName ID="inputUserName" runat="server" />    
<asp:Label Text="User Name" AssociatedControlID="inputUserName" runat="server">

How to make them match, please give me a hand. Thanks


Solution

  • Well, your typing in both the id's for the label, and the UC in markup, so why not just set the associatedControlID="inputUserName_pnlEdit" then? And I would think (suggest) that you if possible include the label in the UC - that way you can manage (set) the label associated id in say the UC page/code.

    You can also of course over-ride the naming of the UC control like this:

        <asp:Label Text="User Name" AssociatedControlID="inputUserName" runat="server">
        <uc1:UserName ID="inputUserName" runat="server" clientIDMode="static" />
    

    However, even better is to use "UserControlID:Name of control inside user control"

    So its "user control id": "then name of control inside of UC" (use a ":" to seperate out the nested control inside of the UC.

    So, you would thus use this markup:

    <asp:Label Text="User Name" 
    AssociatedControlID="inputUserName:pnlEdit" runat="server">
    
    <uc1:UserName ID="inputUserName" runat="server" />
    

    So, you don't show all of the UC markup, but you can use as per above. I mean, it stands to reason that your attempting to associate the label in markup with "most likely" a text box of some sort inside of the UC. Since the UC can have "many" controls inside, then just a simple "ID" will not provide resolution to a given control or markup inside of the UC anyway, would it?

    So, without the UC markup, I am guessing above as to "which" control you want to associate with that exists inside of the UC. However, as noted, use of the ":" does allow a drill down to a given control inside of the UC.