简体   繁体   中英

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?

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');

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM