实现 IStateManager 接口的服务器控件在设定属性时的注意点

设定属性后,要添加一句
ViewState.SetItemDirty() 的调用,这样在后续的阶段,StateBag.SaveViewState() 方法被调用时,才会保存该属性的值。
例子如下:

        public virtual ImageAlign RightImageAlign
        
{
            
get
            
{
                
object o = ViewState["ItemRightImageAlign"];
                
if (o == null)
                    
return ImageAlign.NotSet;
                
else
                    
return (ImageAlign) o;
            }

            
set
            
{
                ViewState[
"ItemRightImageAlign"= value;
                ViewState.SetItemDirty(
"ItemRightImageAlign"true);
            }

        }

通过 Reflector 看到 System.Web.UI.StateBag 类的
SaveViewState() 方法的代码如下,可以验证这一点:

internal object SaveViewState()
{
      ArrayList list1 
= null;
      ArrayList list2 
= null;
      
if (this.bag.Count != 0)
      
{
            IDictionaryEnumerator enumerator1 
= this.bag.GetEnumerator();
            
while (enumerator1.MoveNext())
            
{
                  StateItem item1 
= (StateItem) enumerator1.Value;
                  
if (item1.IsDirty)
                  
{
                        
if (list1 == null)
                        
{
                              list1 
= new ArrayList(5);
                              list2 
= new ArrayList(5);
                        }

                        list1.Add(enumerator1.Key);
                        list2.Add(item1.Value);
                  }

            }

            
if (list1 != null)
            
{
                  
return new Pair(list1, list2);
            }

      }

      
return null;
}

 

posted on 2005-08-01 10:51  NeilChen  阅读(...)  评论(...编辑  收藏

导航

统计