IsPostBack always returns false

Kamyar picture Kamyar · Jul 7, 2011 · Viewed 16.8k times · Source

I've encountered a weird problem. Everytime I refresh the page, IsPostBack is false.
To make sure nothing in my contents or master pages is causing this, I have created an empty web form and fired it up in debug mode. still, on postbacks, I have IsPostBack set to false.

I have enableSessionState="true" and <sessionState timeout="30" /> in web.config.

It's driving me nuts!

Update: I refresh the page by hitting F5. Based on answers this should not cause a postback. I'd like to know when a use refreshes the page (even manually) and prevent some modifications to db).
Is there a solution for this?

Answer

Kyle Trauberman picture Kyle Trauberman · Jul 7, 2011

Refreshing the page (pressing F5 or the refresh button in your browser) is not a postback. A postback occurs when a button is clicked, a dropdown is changed, or some other event on the page that causes data to be sent to the server (via HTTP POST, hence the name 'postback')

Your question doesn't make it clear whether you are refreshing the page manually or posting back to the server via a button click or some other event.

Since you are manually refreshing the page, IsPostBack will always be false.

There are two types of requests (in a sense) in ASP.NET:

  • a regular request (e.g. the user is loading the page for the first time)
  • a postback (e.g. a button was clicked on the page, sending data to the server)

If you want to track if a user has been to a page before in either case, you'll need to track that your self. You can set a variable in the Session to do this:

Session["UserHasVisitedThisPageBefore"] = true;

Then you can check it in place of your current IsPostBack check:

if(Session["UserHasVisitedThisPageBefore"] != null && (bool)Session["UserHasVisitedThisPageBefore"])
{
    // stuff here
}