在什么 ASP.NET 页面事件中分配了 clientID?
我想做这样的事情:
Panel divPanel = new Panel();
divPanel.ID = "divPanel";
this.Page.Controls.Add(divPanel);
string script = "function alertID(){alert("the id is: "+divPanel.ClientID+");}";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "scripttests", script);
但是当我把这段代码放入page_load时,我没有得到完整的id,即ctl00_ContentMain_divPanel,我只得到divPanel。
我还应该使用其他事件吗?我该如何进行这项工作?
I want to do something like this:
Panel divPanel = new Panel();
divPanel.ID = "divPanel";
this.Page.Controls.Add(divPanel);
string script = "function alertID(){alert("the id is: "+divPanel.ClientID+");}";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "scripttests", script);
But when I put this code in page_load, I don't get the full id, which is ctl00_ContentMain_divPanel, I just get divPanel.
Is there another event I should use? How do I make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的示例中,您将直接添加到页面控件集合中。这意味着客户端 ID 应该是 divPanel。也许您期望的客户端 ID 不正确。
In your example you are adding directly to the Page controls collection. This would mean that the client id should be divPanel. Perhaps the client id you expect it to be is the incorrect one.
PreRender 很好,但它也应该在 Page_Load 中工作。
http://msdn .microsoft.com/en-us/library/system.web.ui.control.clientid(VS.71).aspx
您的脚本渲染代码也在 page_load 中运行吗?它们在上面的示例中是在一起的,但也许它们只是复制/粘贴在一起?
如果此代码位于自定义控件中,您还需要将 INamingContainer 接口添加到控件声明中,以便 ClientID 能够按您的预期工作:
http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx
此外,如果是自定义控件,您应该添加到控件本身的 Controls 集合中,而不是添加到包含的页面中。即: this.Controls.Add() 而不是 this.Page.Controls.Add()
PreRender is fine, however it should work in Page_Load as well.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid(VS.71).aspx
Is your script rendering code running in page_load as well? They are together in your example above, but perhaps they were just copy/pasted together?
If this code is in a custom control, you also need to add the INamingContainer interface to the control declaration for ClientID to work as you expect:
http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx
Additionally, if this is a custom control, you should add to the Controls collection of the control itself, not the containing page. ie: this.Controls.Add() instead of this.Page.Controls.Add()