简体   繁体   English

保留控件的属性

[英]Persisting a control's properties

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. 我有一个控件,该控件具有一些需要在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. 但是ClientID的值会在页面的整个生命周期中改变。 It starts out as something like "MyControl1" and then becomes "ctl001_MyControl1". 它以“ MyControl1”之类的名称开始,然后变为“ ctl001_MyControl1”。 So any values applied before it changes are lost. 因此,更改之前应用的所有值都会丢失。

The same thing happens if I use UniqueID instead. 如果我改用UniqueID,也会发生同样的事情。

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 -斯图尔特

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

ViewState[@"somekey"] = ...

尝试在Page_PreRender而不是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: 作为我的意思的一个小例子:

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; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM