ASP.NET: как сохранить состояние страницы на страницах? - PullRequest
0 голосов
/ 24 марта 2011

Мне нужен способ сохранения и загрузки состояния страницы на постоянной основе (сессия).Проект, для которого я нуждаюсь, - это веб-приложение для интрасети, которое имеет несколько страниц конфигурации, и некоторые из них нуждаются в подтверждении, если они собираются быть сохраненными.Страница подтверждения должна быть отдельной страницей.Использование JavaScript невозможно из-за ограничений, с которыми я связан.Это то, что я мог придумать до сих пор:

ConfirmationRequest:

[Serializable]
public class ConfirmationRequest
{
    private Uri _url;
    public Uri Url
    { get { return _url; } }

    private byte[] _data;
    public byte[] Data
    { get { return _data; } }

    public ConfirmationRequest(Uri url, byte[] data)
    {
        _url = url;
        _data = data;
    }
}

ConfirmationResponse:

[Serializable]
public class ConfirmationResponse
{
    private ConfirmationRequest _request;
    public ConfirmationRequest Request
    { get { return _request; } }

    private ConfirmationResult _result = ConfirmationResult.None;
    public ConfirmationResult Result
    { get { return _result; } }

    public ConfirmationResponse(ConfirmationRequest request, ConfirmationResult result)
    {
        _request = request;
        _result = result;
    }
}

public enum ConfirmationResult { Denied = -1, None = 0, Granted = 1 }

Confirmation.aspx:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.UrlReferrer != null)
        {
            string key = "Confirmation:" + Request.UrlReferrer.PathAndQuery;
            if (Session[key] != null)
            {
                ConfirmationRequest confirmationRequest = Session[key] as ConfirmationRequest;
                if (confirmationRequest != null)
                {
                    Session[key] = new ConfirmationResponse(confirmationRequest, ConfirmationResult.Granted);
                    Response.Redirect(confirmationRequest.Url.PathAndQuery, false);
                }
            }
        }
    }

PageToConfirm.aspx:

    private bool _confirmationRequired = false;

    protected void btnSave_Click(object sender, EventArgs e)
    {
        _confirmationRequired = true;
        Response.Redirect("Confirmation.aspx", false);
    }

    protected override void SavePageStateToPersistenceMedium(object state)
    {
        if (_confirmationRequired)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                LosFormatter formatter = new LosFormatter();
                formatter.Serialize(stream, state);
                stream.Flush();

                Session["Confirmation:" + Request.UrlReferrer.PathAndQuery] = new ConfirmationRequest(Request.UrlReferrer, stream.ToArray());
            }
        }
        base.SavePageStateToPersistenceMedium(state);
    }

Кажется, я не могу найти способ загрузить состояние страницы после перенаправления из Confirmation.aspx в PageToConfirm.aspx, может кто-нибудь помочь мне в этомодин

Ответы [ 2 ]

1 голос
/ 24 марта 2011

Если вы имеете в виду состояние просмотра, попробуйте использовать Server.Transfer вместо Response.Redirect.

Если для параметра preserveForm установлено значение true, целевая страница будетиметь возможность доступа к состоянию просмотра предыдущей страницы с помощью свойства PreviousPage.

0 голосов
/ 16 июня 2014

используйте этот код, он отлично работает для меня

public class BasePage
{

protected override PageStatePersister PageStatePersister
    {
        get
        {
            return new SessionPageStatePersister(this);
        }
    }
 protected void Page_PreRender(object sender, EventArgs e)
    {
        //Save the last search and if there is no new search parameter
        //Load the old viewstate

        try
        {    //Define name of the pages for u wanted to maintain page state.
            List<string> pageList = new List<string> { "Page1", "Page2"
                                                     };

            bool IsPageAvailbleInList = false;

            foreach (string page in pageList)
            {

                if (this.Title.Equals(page))
                {
                    IsPageAvailbleInList = true;
                    break;
                }
            }


            if (!IsPostBack && Session[this + "State"] != null)
            {

                if (IsPageAvailbleInList)
                {
                    NameValueCollection formValues = (NameValueCollection)Session[this + "State"];

                    String[] keysArray = formValues.AllKeys;
                    if (keysArray.Length > 0)
                    {
                        for (int i = 0; i < keysArray.Length; i++)
                        {
                            Control currentControl = new Control();
                           currentControl = Page.FindControl(keysArray[i]);
                            if (currentControl != null)
                            {
                                if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox))
                                    ((TextBox)currentControl).Text = formValues[keysArray[i]];
                                else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
                                    ((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
                                else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
                                {
                                    if (formValues[keysArray[i]].Equals("on"))
                                        ((CheckBox)currentControl).Checked = true;
                                }
                            }
                        }
                    }
                }
            }
            if (Page.IsPostBack && IsPageAvailbleInList)
            {
                Session[this + "State"] = Request.Form;
            }
        }
        catch (Exception ex)
        {
            LogHelper.PrintError(string.Format("Error occured while loading {0}", this), ex);
            Master.ShowMessageBox(enMessageType.Error, ErrorMessage.GENERIC_MESSAGE);

        }
    }
    }
...