我能用ViewState找出控件的原始值吗?

时间:2012-12-14 13:39:23

标签: asp.net postback viewstate

在我的ASP.NET网络表单中,说我有类似的东西:

<asp:Literal ID="Literal1" runat="server" Text="abc"></asp:Literal>

现在说我改变后面代码中的文本。该控件已启用viewstate,因此新文本值在整个回发过程中持续存在,这正是我想要的。但在某些情况下,我想将控件重置回原始值(即“abc”),而不必在后面的代码中对其进行硬编码。因此,在不禁用viewstate的情况下,有没有什么方法可以检索控件在首次加载屏幕时的原始值?

由于

2 个答案:

答案 0 :(得分:0)

我不知道如何使用viewstate。但您可以为站点创建一个基页,其中包含跟踪更改的选项,并在加载页面时存储默认值。还有一个班级来做实际的检查。

例如:

更改跟踪器:

 /// <summary>
    /// Class to Track changes in a web page
    /// </summary>
    [Serializable]
    public class ChangeTracker : IDisposable
    {
        //- MEMBER VARIABLES --------------------------------------------------------------------------------------------------------

        #region Members

        private bool m_ChangesMade = false;
        private Dictionary<string, object> m_OriginalValues = new Dictionary<string, object>();
        private Dictionary<string, object> m_ChangedValues = new Dictionary<string, object>();
        private List<string> m_ControlsToIgnore = new List<string>();

        #endregion Members

        //- PROPERTIES --------------------------------------------------------------------------------------------------------------

        #region Properties

        /// <summary>
        /// Gets or Sets the Controls to Ignore (ClientID array)
        /// </summary>
        public List<string> ControlsToIgnore
        {
            get { return m_ControlsToIgnore; }
            set { m_ControlsToIgnore = value; }
        }

        /// <summary>
        /// Gets or Sets the Dictionay of Changed Values
        /// </summary>
        public Dictionary<string, object> ChangedValues
        {
            get { return m_ChangedValues; }
            set { m_ChangedValues = value; }
        }

        /// <summary>
        /// Gets or Sets the Dictionay of Original Values
        /// </summary>
        public Dictionary<string, object> OriginalValues
        {
            get { return m_OriginalValues; }
            set { m_OriginalValues = value; }
        }

        /// <summary>
        /// Gets or Sets Whether changes have been made to the control collection
        /// </summary>
        public bool ChangesMade
        {
            get
            {
                try
                {
                    return m_ChangesMade;
                }
                catch (Exception)
                {
                    throw;
                }
            }
            set { m_ChangesMade = value; }
        }

        #endregion Properties

        #region Constructor

        /// <summary>
        /// Constructor (required for serialization)
        /// </summary>
        public ChangeTracker()
        {

        }

        #endregion Constructor

        #region Methods

        /// <summary>
        /// Adds all relivant controls recursively to the list
        /// </summary>
        /// <param name="oControl">The control to add</param>
        private void AddControls(Control oControl)
        {
            try
            {
                if (oControl != null)
                {
                    //Check whether the control shoudl be ignored
                    if (!this.ControlsToIgnore.Contains(oControl.ClientID))
                    {
                        //loop recursively
                        foreach (Control aControl in oControl.Controls)
                        {
                            this.AddControls(aControl);
                        }

                        if (oControl is IEditableTextControl)
                        {
                            if (this.OriginalValues.ContainsKey(oControl.ClientID))
                            {
                                this.OriginalValues[oControl.ClientID] = (oControl as IEditableTextControl).Text;
                            }
                            else
                            {
                                this.OriginalValues.Add(oControl.ClientID, (oControl as IEditableTextControl).Text);
                            }
                        }

                        if (oControl is ICheckBoxControl)
                        {
                            if (this.OriginalValues.ContainsKey(oControl.ClientID))
                            {
                                this.OriginalValues[oControl.ClientID] = (oControl as ICheckBoxControl).Checked;
                            }
                            else
                            {
                                this.OriginalValues.Add(oControl.ClientID, (oControl as ICheckBoxControl).Checked);
                            }
                        }
                    }
                }
                else
                {
                    throw new ArgumentNullException("oControl");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Checks the controls for changes
        /// </summary>
        /// <param name="oControl">The control to check</param>
        private void CheckControl(Control oControl)
        {
            try
            {
                //Check the control should not be ignored
                if (!this.ControlsToIgnore.Contains(oControl.ClientID))
                {
                    //loop recursively
                    foreach (Control aControl in oControl.Controls)
                    {
                        this.CheckControl(aControl);
                    }

                    if (oControl is IEditableTextControl)
                    {
                        if (this.OriginalValues.ContainsKey(oControl.ClientID))
                        {
                            if (this.OriginalValues[oControl.ClientID].ToString() != (oControl as IEditableTextControl).Text)
                            {
                                if (!this.ChangedValues.ContainsKey(oControl.ClientID))
                                {
                                    this.ChangedValues.Add(oControl.ClientID, (oControl as IEditableTextControl).Text);
                                }
                                else
                                {
                                    this.ChangedValues[oControl.ClientID] = (oControl as IEditableTextControl).Text;
                                }
                                this.ChangesMade = true;
                            }
                        }
                    }
                    if (oControl is ICheckBoxControl)
                    {
                        if (this.OriginalValues.ContainsKey(oControl.ClientID))
                        {
                            if ((bool)this.OriginalValues[oControl.ClientID] != (oControl as ICheckBoxControl).Checked)
                            {
                                if (!this.ChangedValues.ContainsKey(oControl.ClientID))
                                {
                                    this.ChangedValues.Add(oControl.ClientID, (oControl as ICheckBoxControl).Checked);
                                }
                                else
                                {
                                    this.ChangedValues[oControl.ClientID] = (oControl as ICheckBoxControl).Checked;
                                }
                                this.ChangesMade = true;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// Stores the default values
        /// </summary>
        ///<param name="oControl">The control to store</param>
        public void StoreDefaultValues(Control oControl)
        {
            try
            {
                //Reset the Original Values collection
                this.OriginalValues = new Dictionary<string, object>();

                this.ChangesMade = false;

                //Add all relevant controls
                this.AddControls(oControl);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Checks the form for changes
        /// </summary>
        ///<param name="oControl">The control to check for changes</param>
        public void CheckForChanges(Control oControl)
        {
            try
            {
                //Instantiate changed values
                this.ChangedValues = new Dictionary<string, object>();

                //Reset changes made flag
                this.ChangesMade = false;

                //Check controls for changes
                this.CheckControl(oControl);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Dispose of the object
        /// </summary>
        public void Dispose()
        {
            try
            {
                m_ChangedValues = null;
                m_ControlsToIgnore = null;
                m_OriginalValues = null;
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion Methods

    }

基本网页:

/// <summary>
/// Adds Extra functionality to a web page
/// </summary>
public class WebPage : System.Web.UI.Page
{

    #region Properties

    /// <summary>
    /// Gets or Sets the Change Tracker
    /// </summary>
    protected ChangeTracker ChangeTracker
    {
        get
        {
            if (Session[String.Format("ChangeTracker{0}", this.ClientID)] == null)
            {
                Session[String.Format("ChangeTracker{0}", this.ClientID)] = new ChangeTracker();
            }

            return Session[String.Format("ChangeTracker{0}", this.ClientID)] as ChangeTracker;
        }
        set
        {
            Session[String.Format("ChangeTracker{0}", this.ClientID)] = value;
        }
    }

    /// <summary>
    /// Gets or Sets whether changes have been made
    /// </summary>
    protected bool ChangesTracked
    {
        get
        {
            if (ViewState["ChangesTracked"] == null)
            {
                ViewState["ChangesTracked"] = false;
            }

            return (bool)ViewState["ChangesTracked"];
        }
        set
        {
            ViewState["ChangesTracked"] = value;
        }
    }

    #endregion Properties


    #region Events

    /// <summary>
    /// Stores the value of the controls after the load completes
    /// </summary>
    /// <param name="e">order</param>
    protected override void OnLoadComplete(EventArgs e)
    {
        try
        {
            base.OnLoadComplete(e);

            //Dont store on postback
            if (!Page.IsPostBack)
            {
                //Check whether to track changes
                if (this.ChangesTracked)
                {
                    //Store the default values
                    this.ChangeTracker.StoreDefaultValues(this);
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    #endregion Events

}

用法(例如在保存事件上):

       //Check for changes
        base.ChangeTracker.CheckForChanges(this);

        //If changes have been made, flag as dirty
        if (base.ChangeTracker.ChangesMade)
        {
            //Do stuff
        }

正如您所看到的,当页面加载完成时会存储初始值,因此它们都可用于比较,或者在您的情况下,可以重置为原始值。

答案 1 :(得分:0)

您可以尝试使用Page_Init方法从控件中获取文本。视图状态稍后将在页面处理管道中恢复到控制树。因此,如果您访问Page_Init中的文本并将值存储在某个合适的位置,则可以从标记(aspx)文件中获取值。