Oliver
Oliver

Reputation: 11607

Referencing ids unknown at compile time

I'm making a user control to gather all the functionality for popups on my website in one place. When someone instantiates the control, they'll pass in a PopupID attribute, which is assigned to the id of a div inside the control, and will be used to call show() and hide() functions in javascript. I'm going to use content templates so that different stuff can be put inside the control by different kinds of popups.

The html for the popup will look something like this:

<div id="<%=PopupID %>" class="popup box" runat="server">    
    <asp:PlaceHolder runat="server" ID="popupPlaceHolder"></asp:PlaceHolder>
</div>

However, there is a problem: asp.net has the habit of giving controls different IDs when served up to the client than what you write in the html. So the ID of that div might not be <%=PopupID%> It could be somethling like #ctl00_whatever_<%=PopupID%>. Usually I get around this by putting something like:

<script type="text/javascript">
    var ddlCountry0 = '<%=ddlCountry0.ClientID%>';
    var ddlActivity0 = '<%=ddlActivity0.ClientID%>';
    var chkPrivateContacts = '<%=chkPrivateContacts.ClientID%>';;
</script>

In the header for the page. Then when refering to things in the javascript you just do $(ddlCountry0) instead of $('ddlCountry0'). However, I don't see how I can do that in this case, As I don't know the ID of the element until someone instantiates it. What do I do to get around this?

Upvotes: 1

Views: 69

Answers (2)

Oliver
Oliver

Reputation: 11607

In the end, I used ClientIDMode=Static to get around these problems.

Upvotes: 0

trucker_jim
trucker_jim

Reputation: 572

Does the user control have CreateChildControls and OnPreRender methods you can override?

If a control is added and ID set correctly during CreateChildControls...the ClientID property is populated during OnPreRender, at which point the control itself could inject the necessary script block into the body or page header. People often use jQuery to help with this situation:

headerScript.AddLine("var ddlCountry0 = $('[ID$=" & Control.ClientID & "]').attr('id');")

Is that along the right lines?

Upvotes: 1

Related Questions