Rather than using the Session object or storing to the database, I am storing temporary variables that I need persisted to custom ViewState variables. For example, ViewState("MyField1") = 1
When the user hits the browser Rrefresh button, Page.IsPostback is back to False and the ViewState is gone.
My question is. If the user can blow away the Viewstate by refreshing, why would anyone use it?
I know that a Refresh reposts the last submitted page, by why is Page.IsPostback reset to False and the ViewState blown away?
Flame me if you want for creating a potential dup question, but I've read other postings here, and it ain't sinking in...
Update to original post:
I now think that it has to do with postbacks that are performed as a result of clicking on Buttons that are within an UpdatePanel. Can someone help shed some light on this?
When a client refreshes their browser, it re-submits the last full page request issued by the client (which may be a GET or a POST). It does not ever resubmit AJAX requests such as those produced by update panel event triggers ("partial page postbacks").
The fact that Page.IsPostback is false when you refresh the page means that your original request is a GET, so here's what's probably happening:
1) During the initial request, the client sends no form data to the server - hence no hidden field containing view state data (Understanding ASP.NET View State is pretty detailed, but a great read if you want to really understand what's going on). While processing this request, ASP.NET may send some view state back to the client, but the original request is just a URL.
2) When the user clicks a button within an UpdatePanel, they trigger a partial postback during which MyField is set to 1. The UpdatePanel changes the client's view state to reflect the new value.
At this point, if the user submits a POST request by normal means, such as clicking a button, the view state will contain the updated information.
If the user clicks 'Refresh' though, they re-submit the original request from step 1, with no form data and therefore no view state.
Where do you set your ViewState? And where do you re-read your ViewState value? Maybe oyu check its content before asp.net calls the LoadViewState() method.
User hitting refresh and using updatepanel will not work together very well. I quess this is why people say that WebForms provides a leaky abstraction on web programming and some are moving to mvc.
If you're not interested in migrating, I'd give you the advice that do not use updatepanel for too long or big operations, where you can assume that user might refresh the page. Use it for small things like dropdown2 items changing when selection on dropdown1 changes.
Wrapping lots of functionality in one updatepanel will cause trouble, if you just depend on viewstate.
Your question is, "Why would anybody use it."
Viewstate comes in handy for data you know is generated by a post back. Hitting refresh is not a post back, but a fresh request.
So lets say you are browsing a datagrid and you need to know certain bits of data about what they have clicked, on the click event you could store that data in the viewstate and process it during other times in the page life cycle, or subsequent post backs.
ViewState's advantage is that it is just embedded into the HTML, so it is all client side. Where as SessionState is server side, and if you store a great amount of data in the session you can cause your web or db server to work harder to handle that data.
Hope this helps.
Don't know why it works but I had a similair problem and solved it by putting this line in the form_load:
me.myProperty = me.myProperty
where
Public Property myProperty() as String
Get
If Not IsNothing(ViewState("data")) Then
Return CType(ViewState("data"), String)
Else
Return String.Empty
End If
End Get
Set(value As String)
ViewState("data") = value
End Set
Related
I have two controls of interest on a page: a DropDownList and a Button. If the user presses the button, he gets a popup form which, when completed, causes the base page to completely reload, losing the value in the DropDownList. To clarify, it's a refresh, not a postback. I cannot change it to make it a postback. What is the most straightforward way of persisting the selected value in the DropDownList across this page refresh? I cannot avoid the page refresh, because the data entered in the popup is reflected elsewhere on the base page.
Update
I've cobbled together a tenative solution that I'm not terribly happy with: when the user clicks the button, I use javascript to get the current value of the dropdown and pass that with the querystring to the popup being loaded. When the user clicks "Save" on the popup, which causes the data to be saved then the base page to be reloaded, I first store the querystring value into a Session variable. The base page, on loading, looks at said Session variable. If a value is present, it sets the value of the dropdown accordingly and deletes the Session variable.
Although somewhat kludgy, it's the best I can come up with. I know that my Gracious Benefactors dislike using Session variables, but given the page reload, I cannot come up with an alternative. Also, since the Session variable is short-lived, being created shortly before a page is closed then being deleted shortly after the succeeding page is opened, I'm hoping this will be acceptable.
Contrasting opinions, refutating my solution or reasoning, are enthusiastically welcome.
Conclusion
Ultimately, after I described the solution to my Gracious Benefactors, we agreed upon an alternate approach: if a selection is made in the DropDownList, it must be saved before opening the popup. This avoids the whole ViewState problem altogether.
For updated question:
The solution you are trying sounds like it should work. It's not the sort of thing you want to use SessionState for but there are requirements here that make the situation out of the ordinary.
Depending on how you are getting the base page to reload you may be able to add a query string to that which would save you from putting hte value in the SessionState. But I imagine you have probably considered that.
But basically, as Postback values and viewstate are out of the question, SessionState and query strings are you only real option. Oh, unless you are allowed to use HTML5 local storage? (probably not)
From before question update:
If the aspnetForm is being posted back the the value should be persisted automatically by means of the postback values. So the first thing to know is whther your form is going through a postback or if you are refreshing the page in some other way.
If you can't postback the main form then as rockinthesixstring said an Ajax post might be what you need.
Also, if you are doing anything fancy with binding the datasource to the DropDownList or trying to persist the selectedValue yourself then check and re-think that.
I am working on a project which creates controls dynamically for a form in the page_load event, loads in their current values from the database and saves their values (using FindControl) when the user clicks the continue button.
When I added a control statically in the .aspx page and followed their same procedure of loading the value in the page load and saving it on the button press I found that the value would not save correctly. It seems that it wouldn't save because the click event fires after the page_load, so the page_load of the post back reverted the value and the user entered value was not saved.
The strange thing is that by changing the control to be dynamically created just as all the other controls on the page and keeping the loading and saving the same it now works. Even though the page load still creates the control with the old database value.
It seems like a very fundamental asp .net feature here but i'm just unclear as to what is going on. I suspect it is to do with the timing of creation and maybe when the view state kicks in.
Static page controls are created just like dynamic page controls. The difference might be coming in your Page_Load. Whenever you postback all the controls are created afresh which means they are created with their initial values. This happens because after creating the controls asp.net throws away the controls/objects.
So, when the request comes, the first thing that asp.net does it to recreate the controls by looking at their definitions (in the designer files). On each postback they are created and initialized again losing their state in the process.
But after creating the controls Asp.Net loads any viewstate that is sent along with the request which makes people think that the state is always saved at the server.
What might be happening is that either the viewstate is not enabled for your control (in case they are created in designer), in which case you may try using EnableViewState property to true of the control.
Or, when you're doing a Page_Load, you're forcefully re-initializing everything. And in process losing all the control data. If you could post the logic of Page_Load, it might get clarified.
Make sure that:
you are not setting the value again for the static control in Page_Load. The dynamic control are probably getting around it by grabbing the ViewState and form values at a different stage in the lifecycle.
The dynamic controls are added After the static control. Or at least they are added in a different container. Placement in the control's collection can affect the ViewState, although it doesn't look like your scenario / since what you mention seems to be more about the values in the current post.
The save is happening After the Page_Load in response to the corresponding event.
I've run into similar problems in the past (quite a few times actually), but what helped me the most is understanding the ASP.NET Page Lifecycle.
Microsoft has an article on it which describes it pretty well, but this post by Solomon Shaffer really cleared up everything.
I suggest reading them both and coming back with additional questions regarding to a particular state, when to load/save data etc..
Hope this helps.
Marko
Note that you may want to use Page.IsPostBack property to avoid reinitializing values on button clicks and other events.
private void Page_Load()
{
if (!this.IsPostBack)
{
// Assign values to the controls.
}
}
I have a simple form that dynamically presents a data entry form, and the user does a postback and the results are saved to a database. I have created a new version of the form, and based on some information on a database, when the user requests the URL of the old form, I wanted to do a Server.Transfer to the new *.aspx page to generate the page and handle the postback. Since the URL of the page will not change, does that mean the postback gets sent to the original page? Would I then need to check if it's a postback, and if so then call Server.Transfer and allow the form data to be transfered to the new page?
It depends on what you mean by "gets" the postback. The first page will get the form values posted of course, since they are sent from the client. However, how far the first page gets through reacting to the postback information depends on when in the lifecycle you initiate the Server.Transfer. If it is extremely late in the lifecycle (like a click handler), then the first page will have pretty much gone through the entire postback process.
The optional parameter to preserve form values in Server.Transfer dictates whether the second page also reacts to the request as if it is a postback.
Take a look at the HTML source of the page after the Server.Transfer. If the form's action is the new ASPX then you are okay.
It would probably be easier to use a regular redirect. That way you don't have these kinds of issues.
I work on ASP.NET C#. Under button click event I want to save something it's work fine, but after press the refresh button of browser, this event occurs again I want to stop this event.
An article on this subject.
Preventing Duplicate Record Insertion on Page Refresh
Approach 1
A simple solution is to
Response.Redirect back to the same
page after the INSERT command is
called. This will call up the page
without transmitting any post headers
to it. Using Request.Url.ToString()
as the first parameter of
Response.Redirect will cause both the
URL and the page's querystring to be
included in the redirect. The use of
false as the second parameter will
suppress the automatic Response.End
that may otherwise generate a
ThreadAbortedException. A
disadvantage of this approach is that
any ViewState that had been built up
will be lost.
Approach 2
A related approach would be for the form to submit to an intermediate processing page and then Response.Redirect back to the calling page, similar to the classic ASP approach to form processing. This has the same effect as simply using the Response.Redirect in the Button_Click event so it has the same disadvantages, with the added disadvantage of creating another page for the website developer to manage.
Approach 3
The next batch of solutions works by
determining whether the user has
refreshed the page in the browser
instead of pressing the form's submit
button. All of these solutions depend
on the ability of the website to use
Session variables successfully. If
the website uses cookie-based
Sessions, but the user's browser does
not permit the use of cookies, these
solutions would all fail.
Additionally, should the Session
expire these solutions would also
fail.
Approach 4
Should the user somehow manage to
circumvent the above mentioned solutions described
above, the last line of defense is at
the database. There are two methods
that can be employed to prevent a
duplicate record from being inserted
into the database. For each method,
I've moved the SQL code into a stored
procedure, since there are now more
processing steps involved and these
are easier to illustrate in a separate
stored procedure. Note however that a
stored procedure is not strictly
required in order for these methods to
work.
I am using VS 2005, C# 2, ASP.Net 2.0
I am unable to find out how to track that user pressed F5/Ctrl+F5/ Open a new Window(Ctrl + N) in ASP.Net.
I know that there is a Page.IsPostBack property, which tells that a page is loaded in response to an action taken by user.
I am just curious to know, that why isn't there a property as IsRefresh or Page.IsRefresh in ASP.Net, which will return true,
whenever user takes any of the above actions.
Is there a way to know this?
Actually my problem is that i have a DLL using which all of my aspx pages are inherited, I have to
insert some values in a table whenever the page is opened for the first time that's it, if user just opens the page or do not take any action,
an entry should be inserted into the database, but as far as I have tried, I controlled it anyhow using the Page.IsPostBack property, but I got stuck
in the refresh case, as it is inserting records unconditionally.
Similar to using a function in Global.asax (as others have suggested) you could use a session variable "flag". When the page first loads set a session variable and then just check against it in your page load function:
if (Session("visited") != "true"
//page has not been visited, log visit to DB
Just make sure you set the session flag sometime after the above check during the page load.
It won't be exact (sessions can timeout while a page is active, users can completely leave the site and come back in the same browser and the session stays alive, etc) but for your tracking it is much better than counting every page hit in the DB.
Perhaps you want the Session_Start method in the Global.asax file, which will be triggered once at the start of each user session?
In your Global.asax file, add or edit the method:
void Session_Start(object sender, EventArgs e)
{
}
why isn't there a property as IsRefresh or Page.IsRefresh in ASP.Net
Because ASP.NET cannot possibly know. The browser does not send any information that could allow it to determine whether the page is being requested due to a refresh or normal load. You will need to reconsider your requirements: what is the actual purpose of the database logging?
Session_Start method in Global.asax file is fired every time when a browser session is started. You can use this method to count number of unique users on your website.
Session_End method in Global.asax is fired when a session ends (explicitly or timedout). So you can decrement the count here.
Hope the above to example uses of these methods helps you understand how you can use them.
Because of the stateless nature of HTTP protocol there is no way to tell apart the initial load from the refresh
As has already been said. This isn't possible. A request issued due to a refresh is no different to a request issued the first time the page is loaded.
It sounds to me like you are trying to track page views somehow. This is certainly possible though it will require some work on your part. Your best bet is probably to log the URL of the page. You may also want to include the query string in order to differentiate between page loads for different pieces of data (if this happens in your application). You will also want to log the ID of the current user, and the ID of their session.
You can then make sure that you don't insert two page views for the same user for the same page in the same session, effectively filtering out any reloads of a page.
You do need to be aware that this isn't the same as detecting a refresh, what you are detecting is two page views in the same session, this could be a refresh, or it could be use of the back button, or just reloading from the address bar.
My suggestion would be to create a cookie on very first load, then on Page_Load check to see if the cookie exists. If it does, don't insert the record. You can use Session_End to destroy or create the cookie as someone suggested if that works with your application's architecture.