0

我有三个行为非常相似的页面,所以我制作了一个具有 3 种行为的用户控件,我通过添加一个枚举和这个枚举类型的属性来做到这一点。

public enum ucType
    { 
        CustomersWhoHaveAContract, CustomersWaitingForContract, CustomerOfPreReservedContracts
    }

    public ucType UserControlType;

    protected void BtnLoadInfo_Click(object sender, ImageClickEventArgs e)
    {
        switch (UserControlType)
        {
            case ucType.CustomersWhoHaveAContract:
                DoA();
                break;
            case ucType.CustomersWaitingForContract:
                DoB();
                break;
            case ucType.CustomerOfPreReservedContracts:
                DoC();
                break;
            default:
                break;
        }

在我的页面中,我为 UserControlType 赋值,

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ucCustomersWithContract1.UserControlType = UserControls.ucCustomersWithContract.ucType.CustomerOfPreReservedContracts;
        }
    }

但是当我单击按钮时, UserControlType 总是CustomersWhoHaveAContract,这意味着它正在失去它的价值。哪里有问题?

4

1 回答 1

0

你的意思是 ASP.NET WebForms,对吧?
控件不会自动恢复所有数据,有 ViewState 机制。

MSDN 文章
http://msdn.microsoft.com/en-us/library/ms972976.aspx

要修复一个示例,请将您的字段更改为属性:

public ucType UserControlType {
   set {
      ViewState["UserControlType"] = value; 
   }
   get { 
      object o = ViewState["UserControlType"]; 
      if (o == null)
         return ucType.CustomersWhoHaveAContract; // default value
      else 
         return (ucType)o; 
   }
}

它应该可以工作。

于 2012-11-01T11:15:39.180 回答