Are public properties in an ASP.NET code behind supposed to persist between page loads?

时光总嘲笑我的痴心妄想 提交于 2019-12-24 02:45:10

问题


I am trying to capture the HTTP_REFERER upon page_load event of an ASP.NET page, and persist it between postbacks until I need it later. The way I trying to do this isn't working:

public partial class About : System.Web.UI.Page
{
    public string ReferringPage { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ReferringPage = 
              Request.ServerVariables["HTTP_REFERER"];
        }
    }

    protected void ImageButton1_Click(
         object sender, ImageClickEventArgs e)
    {
        Response.Redirect(ReferringPage);
    }
}

I've verified that the referring page's url goes into the property, but when I click the image button, ReferringPage is null! I had thought that the property's value was being stored in the ViewState, so that it would be available upon postback, but this turns out not to be the case. Or am I simply doing it wrong?


回答1:


Every request creates a new instance of the page class, so no, nothing is meant to persist.




回答2:


No, only [most] control properties are persisted on postbacks, so you could save the referring page on a hidden field, or in the ViewState property of your page

I use this snippet a lot:

private string ReferringPage 
{
    get
    {
        return (string)ViewState["ReferringPage "];
    }
    set
    {
        ViewState["ReferringPage"] = value;
    }
}

This will make your ReferringPage work as expected. But be careful, like any hard drug, abuse of ViewState is considered harmful. http://anthonychu.ca/post/aspnet-viewstate-abuse

If you need the ReferringPage variable to persist not only on postbacks, but even when the user navigates to other pages, you just change ViewState to Session, which lets you persist values across navigation from the same (user) session

And last, you may want to take a look at server transfer mechanism in webfoms (with added bonus of links to data persistence methods)

http://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage.aspx



来源:https://stackoverflow.com/questions/7534946/are-public-properties-in-an-asp-net-code-behind-supposed-to-persist-between-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!