保留控件的属性
好吧,是时候问你另一个愚蠢的问题了。
我有一个控件,它有一些需要保留在 ViewState 中的属性。我还需要确保如果控件在页面上出现多次,属性不会被覆盖。
我想写一些类似...
ViewState[String.Format("{0}_{1}", "BaseKey", this.ClientID)] = ...
但是 ClientID 的值在页面生命周期的中途发生变化。它开始时类似于“MyControl1”,然后变成“ctl001_MyControl1”。因此,在更改之前应用的任何值都会丢失。
如果我使用 UniqueID 代替,也会发生同样的事情。
我知道我错过了一些明显的东西,我会把责任归咎于我正在服用的药物,这样我就不会看起来太愚蠢了。
-- 斯图尔特
OK Time for another dumb Q from yours truly.
I have a control that has some properties that need to be persisted in the ViewState. I also need to make sure that the properties aren't overwritten if the control appears more than once on the page.
I thought to write something like...
ViewState[String.Format("{0}_{1}", "BaseKey", this.ClientID)] = ...
But the value of ClientID changes partway through the page's lifecycle. It starts out as something like "MyControl1" and then becomes "ctl001_MyControl1". So any values applied before it changes are lost.
The same thing happens if I use UniqueID instead.
I know I'm missing something obvious, and I'm going to blame the pills I'm taking so I don't look too dumb.
--
Stuart
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您是在用户控件内部执行此操作,如果这是真的,您不需要为视图状态创建唯一的密钥,每个控件的每个实例都管理它自己的视图状态,因此您所需要的只是控件已知的密钥,像这样的东西:
it looks like you are doing this inside the user control, if that is true you do not need to make a unique key for the viewstate, each instance of every control manages it's own viewstate so all you need is a key known to your control, something like that:
尝试在 Page_PreRender 而不是 Page_Load 上执行此操作?
Try doing it on Page_PreRender rather than Page_Load?
不要存储相对于控件本身的输出名称命名的值。为其提供一个唯一的、不变的名称,然后确保所有绑定规则都调整为该名称而不是客户端名称。
编辑:
作为我的意思的一个小例子:
Don't store the value named relative to the output name of the control itself. Provide it with a unique, unchanging name and then make sure all of your binding rules adjust to that name instead of the client name.
Edit:
As a small example of what I mean: