While developing a user control in asp.net I found major difficulty to find html client side element positioned within an update panel.
在asp.net中开发用户控件时,我发现在更新面板中找到html客户端元素非常困难。
The .ascx side contains this:
ascx面包含以下内容:
<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.
我需要在代码后找到对div的引用。
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:
现在,因为还有Ajax (JavaScript)操作div:
- I cannot set runat="server" for that div.
- 我不能为那个div设置runat="server"。
- I must use <%=ClientID%>_MyElement as id'ing convention.
- 我必须使用<%=ClientID%>_MyElement作为id'ing约定。
So assuming the div is going to stay as it is - is there any way to fetch reference to it from the code behind?
假设div会保持原样,有办法从后面的代码中获取引用吗?
2 个解决方案
#1
2
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
在javascript中
var MyElement=document.getElementById('<%= MyElement.ClientID');
#2
1
Try to access your div
from your UpdatePanel
. Example: var div = UpdatePanel1.Controls[0];
尝试从UpdatePanel访问您的div。示例:var div = UpdatePanel1.Controls[0];
#1
2
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
在javascript中
var MyElement=document.getElementById('<%= MyElement.ClientID');
#2
1
Try to access your div
from your UpdatePanel
. Example: var div = UpdatePanel1.Controls[0];
尝试从UpdatePanel访问您的div。示例:var div = UpdatePanel1.Controls[0];