G.Y
G.Y

Reputation: 6159

How to find a client side element in an update panel from code behind?

While developing a user control in asp.net I found major difficulty to find html client side element positioned within an update panel.

The .ascx side contains this:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
   <ContentTemplate>
      <div id="<%=ClientID%>_MyElement">
      </div>
   </ContentTemplate>
</asp:UpdatePanel>

And I need to get a reference to that div in my code-behind.

protected void Page_Load(object sender, EventArgs e)
{
    if(IsPostBack)
    {
        //var c = UpdatePanel1.FindControl("<%=ClientID%>_MyElement"); //<-not working.
        //:
        //get some values from c
        //:
    }
}

Now, since there is also Ajax (JavaScript) manipulating that div:

  1. I cannot set runat="server" for that div.
  2. I must use <%=ClientID%>_MyElement as id'ing convention.

So assuming the div is going to stay as it is - is there any way to fetch reference to it from the code behind?

Upvotes: 1

Views: 2935

Answers (2)

F&#233;lix LD
F&#233;lix LD

Reputation: 372

Try to access your div from your UpdatePanel. Example: var div = UpdatePanel1.Controls[0];

Upvotes: 1

sangram parmar
sangram parmar

Reputation: 8726

Try this:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
   <ContentTemplate>
      <div id="MyElement" runat="server">
      </div>
   </ContentTemplate>
</asp:UpdatePanel>

in code behind

protected void Page_Load(object sender, EventArgs e)
{
    if(IsPostBack)
    {
        var c = MyElement;

    }
}

in javascript

var MyElement=document.getElementById('<%= MyElement.ClientID');

Upvotes: 2

Related Questions