Page Refresh Causing Postback - Asp.net - c#

I have a form inside a Usercontrol, & calling this from a page say index.aspx.
After submitting the form and clicking refresh, it again causes postback.
So, I tried to maintain a flag in a viewstate as '1' after data saved and '0' when it is initial page load.
But why does the viewstate change its value to 0 with refresh.
How to resolve this.
MyForm.ascx.cs
protected void Page_Load(object sender, EventArgs e){
if(!IsPostBack){
ViewState["DataSaved"] = 0;
}
}
protected void btnSubmit_Click(object sender, EventArgs e){
if (Page.IsValid && Convert.ToInt32(ViewState["DataSaved"]) == 0){
//save data;
ViewState["DataSaved"] = 1;
} else{
ViewState["DataSaved"] = 0;
}
}

On refresh the page is reverted as it was initially (you came to this page via GET request).
So Viewstate is returned to its initial state and all changes made to it are lost. This is normal behavior. The behavior you expect is more like a session, so you might try using a session - it will maintain its state between requests.
Look at this for general understanding of page life cycle in .net:
http://msdn.microsoft.com/en-us/library/vstudio/ms178472%28v=vs.100%29.aspx
And this for explanation of Viewstate:
http://msdn.microsoft.com/en-us/library/ms972976.aspx
Both will be very helpful for you!
Good luck.

To make it simple, ViewState is saving inside user machine, and Session is saving inside server machine (access by cookies).
ViewState will be refresh whenever page IsPostBack or !IsPostBack
Session, however, will not.
In your case, i think you should use Session, instead of ViewState.
To understand more, you can go through ASP.NET Life Cycle. It's always good to learn from basic

Use a Session instead of the ViewState.

Related

C# web forms - How to pass data from master page to master page when redirect is on web form?

When on master page I have dropDownList with event. When event Raise I want to load/redirect webForm.aspx. In this webForm.aspx I want to load data based on dropDownList selected item. At the same time I want to load again dropDownList and select Item on which clicked was.
I created some solution, where I was using Response.Redirect("webform.aspx?courseID=4") on masterPage.
Is this good approach to this problem? I think there must be better, but I cant see it.
Thanks for answers.
One way is your solution: to use querystring.
The second way is: on dropdownlist's value changing you changing value of some session value (e.g. *Session["course_id"]), then Response.Redirect("webform.aspx") and restore by Session["course_id"] value.
protected void ddlCourses_SelectedIndexChanged(object sender, EventArgs e){
Session["course_id"] = ddlCourses.SelectedValue;
Response.Redirect("webform.aspx");
}
ABOUT YOUR SECOND QUESTION (HOW TO TAKE ROUTE VALUE FROM MASTER PAGE). I will give just brief explanation and a little example.
Create in your master page some method:
protected void IWantToWarkWithRouteValue(){
//here you will do something
//and to take value from routing, just use Session["myValue"] (I will explain this value later)
}
You should call this method in Page_Load, not in Pre_Init or Init
Then in your Course.aspx (caz' you using routing here) create the next method:
protected void SetCourseSessionFromTheRoute(){
if (Page.RouteData.Values["courseID"] != null)
Session["myValue"] = Page.RouteData.Values["courseID"].ToString();
}
And call this method in Page_PreInit:
protected void Page_PreInit(object sender, EventArgs e){
SetCourseSessionFromTheRoute();
}
Thanksgiving to ASP.NET page's life cycle, you may do anything you need.
You may read about page's lifecycle here
As I said, it is just an example. You may find a better solution.
Hope it helps.

viewstate disappears on response.redirect

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?
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.
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
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.

Activating a ASP Multiview control's view from other page without querystring/session

I was looking for an alternative that may be used to activate a multiview control of other page without passing a querystring/session variable.
Basically, my Home.aspx page has a link that takes us to a specific page say "NewPage.aspx". The NewPage.aspx page has a multiview control that has three child views.
I want to click on the link of the Home.aspx and go to NewPage.aspx with MultiView1.ActiveViewIndex=1. Please remember that I do not want to pass any querystring variable as that link already contains some encrypted data as querystring and adding another variable can cause the data to corrupt. Maintaining a session isn't a solution as well because the application is quite big.
Any inbuilt method that can activate that view? (I don't seem to be talking practical but any help is really appreciated)
If you are asking about how navigate to this page I would wire up a button event (I prefer to do so in OnInit). Something like this:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.btnlinkclick.Click += new EventHandler(btnlinkclick_Click);
}
void btnlinkclick_Click(object sender, EventArgs e)
{
this.MultiView1.ActiveViewIndex = 1;
}
This should work for you.

Session variable and Masterpages

I want to log a users session on my site. I was hoping to just set a session variable. But the initialisation of it is giving me problems.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["SESSION_GUID"] == null)
{
Session["SESSION_GUID"] = Guid.NewGuid().ToString();
Response.Redirect(Request.Url.ToString(), true);
return;
}
lnkUpload.Visible = (Session["LOGGED_IN"] != null);
btnLogout.Visible = (lnkUpload.Visible);
}
It seems that the masterpage is creating the variable OK, but the rest of the pages load (ones using that master page). So in my log, I am seeing TWO hits. One with no session ID set, and the second hit has a session id.
Any idea why the child page of this masterpage is loading twice? This only happens on the first request to the site. After that, the session is working fine and we only get one hit.
The Page_Load event of the content page will be called before the Page_Load of the master page as seen in steps 6-7 in the ASP.NET Page Lifecycle
The master page Page_Init event is called before the content page Page_Init event though, so if all you're doing is checking for Session, probably best to handle it in the Page_Init of the master page and redirect there. This could cause problems based on how other code in your project looks but conceptually, one of the first things you are wanting to do is check Session and handle properly so, you don't need page/controls to load before handling the redirect.
Try doing a Response.End() in the master page. This will halt the remaining markup from being rendered.

If one page executes a Response.Redirect() to a different web page, can the new page access values in asp.net controls from the original page?

I have a text string value that I'd like to persist from one web page to another without using query strings or the session/view states. I've been trying to get the ASP http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx">HiddenField control to pass information from one web form to a different form.
All the hiddenfield control examples that I've seen is to preserve round trips from the client to the server for the same form.
Is there way for a form to access the ASP controls (and their values) from the previously-rendered form? Or is the initial form simply disposed of in memory by the time the second form executes it's OnLoad method?
Quick answer is no. As others have noted, you can use Server.Transfer and then you can - however this is to be used with caution. It is a "server side redirect" eg.
Your user is on http://mysite.com/Page1.aspx they click a button and you perform a Server.Transfer("Page2.aspx"). Page2.aspx will be rendered in their browser, but the URL will still be Page1.aspx, this can cause confusion and mess up back/forward navigation.
Personally I would only use Server.Transfer as a last resort - in the world of the web, sharing data across pages generally means you need to use a storage mechanism; Cookie, QueryString, Session, Database - take your pick.
You can't get the previous page fields with Response.Redirect.
You can with cross page posting :
if (Page.PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.Text;
}
}
If both pages live in the same application you can use Server.Transfer:
firstpage.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Server.Transfer("~/secondpage.aspx");
}
secondpage.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Page previousPage = (Page) HttpContext.Current.PreviousHandler;
Label previousPageControl = (Label) previousPage.FindControl("theLabel");
label.Text =previousPageControl.Text;
}
A somewhat better solution would be implementing an interface on your first page where you expose properties for the values needed by the second page.
I would presume that the Response.Redirect() sends a Location: HTTP header to do a redirect.
As HTTP is stateless, I'd also presume that these variables are inaccessible.
There are however, solutions.
Print a form with hidden fields, and use javascript to submit it
Redirect in the code internally (load up the thing it needs to get to manually)
Store the data in some temporary database table somewhere, and pass along a unique ID
However, from my experience, I can't understand why you might need to do this (other than re-submitting a form after a user authentication - which hopefully you should be able to use method 2 for
Remember, a Response.Redirect instructs the browser to issue another request to the server. So far as the server is concerned, this next request is indistinguishable from any other incoming request. It's certainly not connected to a previous form in any way.
Could you explain your aversion to storage in the session, so we can propose some viable alternatives?

Categories