viewstate disappears on response.redirect

2019-07-06 16:35发布

On my asp.net c# page I have two text boxes(start and end dates) with ajax CalendarExtenders. The user selects a start date and then an end date. On selecting the end date, I bind my grid as shown below;

 protected void calEndDate_TextChanged(object sender, EventArgs e)
    {
        BindGrid();
    }

In the grid I have a command button with the following code

 protected void gvAllRoomStatus_RowCommand(object sender, GridViewCommandEventArgs e)
    {    
        if (e.CommandName == "Manage")
        {    
            GridViewRow row = gvAllRoomStatus.Rows[Convert.ToInt16(e.CommandArgument)];    
            int BookingID = Convert.ToInt32(row.Cells[1].Text);              

            DataClassesDataContext context = new DataClassesDataContext();
                Session["BookingID"] = BookingID;
                Response.Redirect("CheckIn.aspx");
        }
    }

When the user goes to that page and clicks the back button all the selected dates and the gridview data disappears. Any ideas why the viewstate is disappearing?

3条回答
时光不老,我们不散
2楼-- · 2019-07-06 17:16

In my opinion the issue you have is because you make auto post backs with calEndDate_TextChanged using Ajax.

After your submit, when you press the back button the browser can not remember neither can save what you have change with all that auto post data with Ajax calls, and you lose them.

For me remove the Text Change auto post back, remove the Ajax because you do not needed and make a regular full post back when the user submit their data.

Then when you make back with the browser, browser load the previous state and most of the browsers remember what and all the input of the user. Also on that back the viewstate is the same as previous because did not have change from the Ajax.

查看更多
疯言疯语
3楼-- · 2019-07-06 17:24

Viewstate to look at it in a very simplified way is to see it as a carbon copy or cache of the last state of the page you are currently on. Therefore doing a redirect to any page, even the same page itself, is essentially a fresh start. The viewstate no longer applies as for all intent and purpose, you are on a new page.

As Tim suggests in his post, either store the required data as a session variable or use a server.transfer.

Take a look here for a nice overview of viewstate: http://www.codeproject.com/Articles/37753/Access-ViewState-Across-Pages

查看更多
Rolldiameter
4楼-- · 2019-07-06 17:28

ViewState belongs to the current Page.

Have a look: http://www.codeproject.com/Articles/37753/Access-ViewState-Across-Pages

Yes, we can access the viewstate variables across pages. This is only possible if Cross Page Posting or Server.transfer is used to redirect the user to other page. If Response.redirect is used, then ViewState cannot be accessed across pages.

So you could use Server.Transfer instead or use the Session.

查看更多
登录 后发表回答