UserControl丢失数据

时间:2012-11-01 07:25:12

标签: c# asp.net-mvc user-controls enums

我有三个行为非常类似的页面,所以我用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,这意味着它正在丢失它的值。问题在哪里?

1 个答案:

答案 0 :(得分: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; 
   }
}

它应该有用。