How to Persist a Control's Value/Text Property Between Page Refreshes? - asp.net

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.

Related

ASP.NET how to pass a reference to a particular control

I'm generally an ASP.NET MVC guy, so the "standard" ASP.NET stuff is a little difficult for me to wrap my brain around. I've tried looking for the answer, but the keywords I'm using seem to be too generic... I get a lot of close answers, but not what I'm actually looking for.
I have a grid that is populated from a data set. One of the fields is a dropdown with 4 possible statuses. When the user selects a status, an event is fired in the codebehind to make the change in the db immediately.
There is a particular status that I need to confirm, because once it's selected, it's irreversible. Figuring out how to have the back end pop up a confirmation box was annoying, but I think I have that part done now.
The problem is, if the user confirms that the status they selected for the dropdown was intended, I need to disable any further changes to that dropdown, either by disabling the control or by removing the row altogether. With this requirement, I imagine I need to pass a reference to the specific control that fired the event back to the script, so that it can pass it through the postback, where I would need to consume it.
I have no idea how to pass a reference to the control (what can be used as a reference?) and I have no idea how to use that reference in the postback.
Any help would be greatly appreciated.
;p i was waiting for you to find my post on the issue lol.
but to put it simply, you postback to the page, all members are still available to you if you instantiated something in codebehind. if not, then use FindControl to pull them from DOM. here's the passing values stuff.
as long as you don't kill the lifecycle, you're fine: Passing dropdownlist selected value to another page's dropdown list
and here is the linkspam (full docs): How do I keep TCP/IP socket open in IIS?
probably the articles on session-state and page lifecycle will be of most use.
To prompt the user for confirm add this attribute to dropdownlist.
onchange="return confirm('Confirmation Message');"

Maintaing changes on the previous page

I have a page in asp.net by clicking on the grid in the page it takes me to the detail page,on this page i have a back button (not browser back) by clicking on the button it takes me again to the search page.
i want to see the page with changes which i have made before coming to the detail page,also i want to disable back button of browser.
i dont want to use session variable or viewstate variable.
is there any property for this scenario.
yours sincerely
Talha khan
You can't disable the browser back button. End of story. Sorry.
What changes are you making to the grid, where is it getting it's data from? You could use a cookie to store the previous pages' state if you don't want to use session or viewstate.
If the the amount of data you need to track is relatively small (in your case this would probably be a search query) you can use query string to pass the state to the detail page (which can be later passed back to the search page).
You can also use browser cookies to persist the state but I wouldn't do that (at least because they're not designed for this kind of interaction).
-- Pavel
There are several ways to solve this.
The first that comes to mind is to change the page to AJAX. AJAX would not force a page jump forward, hence there will be nowhere to go back to.
The second way is to have a check on the previouis page, for example set "Session("if_search_go_here") = Request.Url.PathAndQuery" and unset it at the right place. If this is set then the search page will just forward you to the detils page again.
probably more. :)

What are the main differences of defining a control statically or creating it dynamically on page load?

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

ViewState lost on refresh in UpdatePanel?

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

Why does my session variable appear to empty itself in ASP.NET?

I have user control on a ASP.NET web page, which contains a GridView and a radio button selector.
In the underlying middle tier I have a thread which goes to the database and then raises an event to say "I have some data" my User control handles this event and sets a Session Variable.
This works and I can see the event being handled and the Session variable gets the new data.
However when i go to use this session variable when the selected index of the Radio button selector changes the Session variable reports as "Nothing"
I have ensured that the obvious (i.e. spelling, Sessions switched on etc) are correct.
The GridView and radio button selector are encapsulated in the same Update panel.
Check that if your UpdatePanel - updatemode is set to 'Conditional'? also Child as triggers? I would first start by putting a stop in your page load, see whats happening from there. Do a search for all places where you populate that session variable and put a stop. You may be surprised, I have often found that page lifecycle gets confusing even though I thought I understood it. Alt - post some code and we can step through.
Yeah, sounds almost like a problem with order of operations or not checking for postback on a page load or something?
Like JamesM suggested, running your website in debug mode should really help identify the problem. You can bring up your watch window and set it for the Session variable you're looking for, then set breakpoints all over and check the value at each stop to divide and conquer the code.

Resources