保留控件的属性

发布于 2024-10-14 10:29:05 字数 417 浏览 2 评论 0原文

好吧,是时候问你另一个愚蠢的问题了。

我有一个控件,它有一些需要保留在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

め七分饶幸 2024-10-21 10:29:05

看起来您是在用户控件内部执行此操作,如果这是真的,您不需要为视图状态创建唯一的密钥,每个控件的每个实例都管理它自己的视图状态,因此您所需要的只是控件已知的密钥,像这样的东西:

ViewState[@"somekey"] = ...

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:

ViewState[@"somekey"] = ...
水溶 2024-10-21 10:29:05

尝试在 Page_PreRender 而不是 Page_Load 上执行此操作?

Try doing it on Page_PreRender rather than Page_Load?

凉城凉梦凉人心 2024-10-21 10:29:05

不要存储相对于控件本身的输出名称命名的值。为其提供一个唯一的、不变的名称,然后确保所有绑定规则都调整为该名称而不是客户端名称。

编辑:
作为我的意思的一个小例子:

MyControl ctrl1 = new MyControl();
ctrl1.ID = "MyControlA";
ctrl1.Text = "Some text";
ViewState[ctrl1.ID] = ctrl1.Text;

MyControl ctrl2 = new MyControl();
ctrl2.ID = "MyControlB";
ctrl2.Text = "Some other text";
ViewState[ctrl2.ID] = ctrl2.Text; 

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:

MyControl ctrl1 = new MyControl();
ctrl1.ID = "MyControlA";
ctrl1.Text = "Some text";
ViewState[ctrl1.ID] = ctrl1.Text;

MyControl ctrl2 = new MyControl();
ctrl2.ID = "MyControlB";
ctrl2.Text = "Some other text";
ViewState[ctrl2.ID] = ctrl2.Text; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文