回 帖 发 新 帖 刷新版面

主题:[转帖]asp.net中ListView的一个Bug

今天一个学生问了一个问题,他的程序监听ListView的ItemCreated事件,然后在事件响应函数中用FindControl定位 InsertTemplate中的控件,然后使用控件的ClientID进行JavaScript的注册:

if (e.Item.ItemType == ListViewItemType.InsertItem) {
     TextBox TextBox1 = (TextBox)e.Item.FindControl("FirstNameTextBox");

但是运行以后发现取到的ClientID和最终渲染到浏览器的ID不一样,经过我搜索,在微软的网站上找打了官方解释,确实是ListView的一 个Bug,这个Bug在ASP.Net 4.0中仍然没有修复。

文章地址:http://connect.microsoft.com/VisualStudio/feedback/details/328680/problem-accessing-controls-clientid-on-asp-net-listviews-itemcreated

On any ASP.NET ListView's ItemCreated event.
If one trying to access "ClientID" property of a certain control 
inside ListView's InsertItemTemplate.
The actual client ID of that control, when it is rendered into HTML, will be corrupted
and hence the postback of that control won't fire any event 
or the data cannot be bound.

微软的回复:

Thanks for reporting this issue. There is a bug in how System.Web.UI.Control caches its UniqueID if it has been accessed before its NamingContainer has been added to the control tree. This is exactly the bug you are seeing -- your custom control accesses its UniqueID property before its parent GenericWebPart (a NamingContainer) has been added to the control tree.

Unfortunately, due to performance and compatibility concerns, we are unable to fix the root cause of this issue in System.Web.UI.Control. Here are the workaround that may help your scenario:

Your current code:

protected void ListView1_ItemCreated(object sender, ListViewItemEventArgs e) {
if (e.Item.ItemType == ListViewItemType.InsertItem) {
     TextBox TextBox1 = (TextBox)e.Item.FindControl("FirstNameTextBox");
     if (TextBox1 != null) {
    string s = TextBox1.ClientID;             
    <<< Error: accessing ClientID here as too early in the page lifecycle
     }
}

 

微软给出的解决方案是使用ItemDataBound事件,但是ItemDataBound事件中不能处理InsertTemplate中的内容。 我的解决方案是,虽然找到的控件的ClientID和最终生成的不一样,但是仍然能够保证唯一性,因此可以给控件设置一个额外的属性,比如myId,然后 用JQuery来通过这个myId来定位控件,大体思路:

textbox1.Attributes["myId"] = textbox1.ClientID;

textbox2.Attributes["onblur"] = "$('input[myId="+textbox1.ClientID+"').text('test')";

或者完全用JQuery的next之类的方法进行定位不依赖于ID。

转载请注明来自: http://www.caodong.net/Article/834.html 

回复列表 (共2个回复)

沙发


还没遇到过这样的问题

板凳


CSDN编程皇冠交流总130945818,从这里开始.编程 技术.综合交流-新群成立,招募活跃群管

我来回复

您尚未登录,请登录后再回复。点此登录或注册