保存视图状态和加载视图状态中的问题

时间:2015-10-04 06:22:47

标签: c# state-management

创建自定义服务器控件

尝试将属性存储在视图状态但在回发时我无法获取先前存储在状态中的值。  以下是代码

  private int attachmentId;
    public int AttachmentId
    {
        get { return attachmentId; }
        set { attachmentId = value; }
    }

  private string attachmentName = string.Empty;
    public string  AttachmentName
    {
        get { return attachmentName; }
        set { attachmentName = value; }
    }


 protected override void LoadViewState(object savedState)
    {
        object[] state = (object[])savedState;
        base.LoadViewState(state[0]);
        this.attachmentName = (string)state[1];
        this.attachmentId = (int)state[2];           
    }

 protected override void OnLoad(EventArgs e)
    {
        if(!IsPostBack)
        {
        this.AttachmentName ="HelloText.txt";
        this.AttachmentID = 10;
         }
    }

 protected override object SaveViewState()
    {
        object[] state = new object[3];
        state[0] = base.SaveViewState();
        state[1] = this.attachmentName;
        state[2] = this.attachmentId;

        return state;
    }
第一页上的

加载值在View状态中添加 如果有任何回复将会发生值,现在没有发生的值可以帮助我

1 个答案:

答案 0 :(得分:0)

您应该考虑以下选项来实现这一目标。它是更加干净利落的方式。

Class / Enum的示例

public Color XXX
{
    get { return (Color)ViewState["XXX"]; }
    set { ViewState["XXX"] = value; }
}

布尔

的示例
public bool AskForUpdate
{
        get
        {
            if (ViewState["AskForUpdate"] == null)
                return false;
            else
                return Convert.ToBoolean(ViewState["AskForUpdate"]);
        }
        set { ViewState["AskForUpdate"] = value; }
}

整数示例

 public int RevisionID
    {
        get
        {
            int revisionID = 0;
            int.TryParse(hdnRevisionID.Value, out revisionID);
            if (revisionID == 0)
            {
                if (Request.QueryString["ProposalID"] != null)
                {
                    if (int.TryParse(Request.QueryString["ProposalID"].ToString(), out revisionID))
                    {
                        hdnRevisionID.Value = revisionID.ToString();
                        return revisionID;
                    }
                }
            }
            else
            {
                return revisionID;
            }
            return revisionID;
        }
    }

字符串示例

 public string userGroup
    {
        get
        {
            if (ViewState["userGroup"] == null)
                return "";
            return (ViewState["userGroup"].ToString());
        }
        set { ViewState["userGroup"] = value; }
    }

在你现有的实现上也应该工作。你没有在LoadViewState中调用基本方法。

  base.LoadViewState(savedState);