Question

I'm stuck with this dynamic control ID generation,if I put my controls(say Button) in ContentPage (which is inherited by MasterPage) inside <asp:Content></asp:Content> when the page is rendered in the browser then the control Id are changed ,I read ScottGu article on 'clientIDMode' and I thought my problem is over so I set 'clientIDMode' inside 'Web.Config'

<pages clientIDMode="Static"></pages>

But the problem persists I can't refer my controls from code behind like this,

        //ctl00$Cntnt$Button1 name works but its dynamically created
       if (ScriptManager1.AsyncPostBackSourceElementID == "Button1")
        {
            Label1.Text = "Async PostBack occured @ " + DateTime.Now.ToLongTimeString();
        }

ASP.net Markup:

<asp:Button ID="Button1" runat="server" Text="Refresh me" onclick="Button1_Click" />

Browser Side Markup:

<input type="submit" name="ctl00$Cntnt$Button1" value="Refresh me" id="Button1" />

Q) Can't I use just the Id of controls which I have specified in the Markup (as if I don't have any MasterPage)?

P.S: On AsyncPostback I want to perform certain operations based on specific Button which made AsyncPostback ,to do that I have to check value from AsyncPostBackSourceElementID which unfortunately returns modified ControlID

Was it helpful?

Solution

The ClientIDMode doesn't matter because AsyncPostBackSourceElementID is actually returning the name of the button rather than the ID. However, you can easily get the name of the button through the UniqueID property:

if (ScriptManager1.AsyncPostBackSourceElementID == Button1.UniqueID)
{
    //do whatever
}

I think you're misunderstanding the purpose of ClientIDMode. The IDs that ASP.NET generates apply to the client-side, and in the code-behind you can still access controls by the IDs assigned to them in markup.

<asp:Panel ID="Panel1" runat="server">
    <asp:Label ID="Label1" runat="server" />
</asp:Panel>

When this is rendered, a unique identifier (ClientID) will be generated for each control using a combination of the ID you assigned and the IDs of any ascendant naming containers. In this case Panel1 is the naming container, so the generated ID would be:

<span id="ctl00_Panel1_Label1"></span>

However, in the code-behind you can still access the control by the original ID you assigned to it:

var labelText = Label1.Text;

The generated ID only comes into play on the client-side, where for example you might need to access the control from JavaScript; you would then can the ClientID to find it.

var labelText = document.getElementById("<%=Label1.ClientID%>").innerText;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top