数据绑定控件ListView事件ItemCreated的Bug
习惯性的用TextBox.ClientID取来服务端渲染到客户端的ID,而在ListView的ItemCreated事件中却怎么也取不到。
我的一个WareAllMoneyTextBox控件,
ClientID="ctrl6_WareAllMoneyTextBox“ 而渲染到客户端变成了id="ListView1_WareAllMoneyTextBox" 。
目前发现的解决方法有三个:
方法一:
仔细观察两个ID会发现是有相同之处的,我通过代码生成了数个类似代码,研究结果也是一样的。当需要在服务端设置客户端的Js或者样式等等的时候,可以后台直接使用ListView1_加上控件的后台名字,当然这样做当控件多的时候会很麻烦。在不同的ListView中前面加的东西应该也是不一样的。
方法二:
直接使用Attributes再生成一个Id到客户端去,然后在客户端的均对新生成的ID的控件做操作。
textbox1.Attributes["myId"] = textbox1.ClientID;
textbox2.Attributes["onblur"] = "$('input[myId="+textbox1.ClientID+"').text('test')";
方法三:
完全用JQuery的next之类的方法进行定位不依赖于ID。
微软官方回复:
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: