Are public properties in an ASP.NET code behind supposed to persist between page loads?
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.开发者_C百科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?
Every request creates a new instance of the page class, so no, nothing is meant to persist.
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
精彩评论