ASP.NET Hidden Field Persistence During Life Cycle - asp.net

I feel like I may be overlooking a fundamental concept of the page life-cycle here and have been (either because I can't figure out the right keywords or it hasn't been asked) unable to locate an existing answer so forgive me if this has been asked.
Basically, I need to persist a mutable object between the client side and the server side. Since the viewstate is encrypted/serialized and the session state is server-side only, my solution was to use a hidden field--easy enough, right? Well here's my problem... it seems as though it's working but the data isn't being propagated as I would've expected.
My expectation was this:
Page is loaded for the first time. Server-side class recognizes that the hidden field is empty, initializes the container class, serializes the class to a JSON string and writes that value to the hidden field.
Page_Init: Unavailable.
Page_Load: Unavailable.
Page_LoadComplete: Available.
Server processing completes, object is now available for use by client code.
Object in hidden field is mutated by client code. Client code then fires a postback to the server (via a button).
Server-side processing begins...
Page_Init: Unavailable.
Page_Load: Available, including client-side changes.
Page_LoadComplete: Available, including client-side changes.
All is right in the world, a double-rainbow shines outside my window and a magical unicorn gives me a wink and a nod.
My observation is this:
Page is loaded for the first time. Server-side class recognizes that the hidden field is empty, initializes the container class, serializes the class to a JSON string and writes that value to the hidden field.
Page_Init: Unavailable. (As expected)
Page_Load: Unavailable. (As expected)
Page_LoadComplete: Available. (As expected)
Server processing completes, object is now available for use by client code.
Object in hidden field is mutated by client code. Client code then fires a postback to the server (via a button).
Server-side processing begins...
Page_Init: Unavailable. (As expected)
Page_Load: Available, but not updated with changes made on the client-side. (Unexpected).
Page_LoadComplete: Available, including client-side changes. (As expected)
A dark cloud forms over my cubicle and I begin to contemplate whether or not my laptop would survive the second-story fall off the balcony.
Conclusion
This is causing me a bit of confusing for a couple reasons... the first is that I've never used the "LoadComplete" event before and can't seem to find any examples that suggest it's necessary to or even that it should be done that way. The second is that by the time load complete is raised, other events that rely on the data from the client side have already been fired.
Any help/explanation/suggestion; hell, even criticism is appreciated!
Thanks, Jason

I'm answering this in the hope that this helps save someone else a few hours. After much trial and finally success, I learned that you can get a HiddenField value during the OnInit event. Given a HiddenField with an ID of hidValue, the key line is:
string strValue = Request.Form[hidValue.UniqueID].ToString();

I've ripped a lot of hair on ASP.NET lifecycle :-). I would advise you this:
bind to control events
avoid binding or overriding to page
events
In this case, you should have a protected HiddenField declared in your page/user control. So you really want to bind to the ValueChanged event, and forget about the rest.

Explaination
You can update HiddenField values in javascript and get them back at the server.
If you want your object to be available after Load, using LoadComplete is ok.
If you want this object to be available to all controls when they load, the earliest you can get the data from inputs is by overloading PreLoad and creating your object there.
There is no problem with your logic.
Conclusion
There is some bug in your implementation of it.
Lets take a look at the code now.

Related

SignalRv2 - Passing values to Hub

Ill try my best to explain this. In my Hub code, i have instantiated the ConnectionMapping class. It was taken from here http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections#inmemory .
This ConnectionMapping requires a unique key for its dictionary. I have a webform code-behind called default.aspx.cs. In this code behind, I will get a unique Login Username inside the Page_Load event. How do i pass this username to the Hub to add it to the ConnectionMapping?
I tried.
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
But i dont know what im doing after doing this. Help.
The short answer is, you don't. Not with the code you have. The issue is this sequence:
Client requests page
Server-side code runs (Page_Load)
Resulting HTML/JS is sent to client
Client connects to SignalR
At this point, you would presumably add to the ConnectionMapping. The issue being of course, that any data/variables in Page_Load are no longer available, and you'd have no way of mapping the connection you just received to that page request even if they were.
Your website needs to hold on to some piece of information, perhaps that username, and pass it to the hub on connection (possibly via the query string). The data could even be stored in the page as part of the Page_Load event (in a hidden div or through some other mechanism).
Now you have both pieces of information at the same time, and can add to the mapping normally.

Using a class in PostBack

I am totally new to classes and OOP, so please bear with me.
I am creating a large scale web app which I'm trying to keep tidy by creating my own classes.
For instance I have a Public Class Product which has several properties. One way I am using it is on page load a product ID is assigned to the ID property which in turn gets the details for that product and assigns the various data to the other properties. So within my code I can used for example product.price or product.description and get the appropriate values. This has worked fine, but I found that because the class was initiated on page load it was getting the data from the DB each time that the page refreshed. I stopped this by using an If Not IsPostback to initiate the class. This meant that the data was pulled in only on the initial page load. So far so good.
I then needed to compare a value in a textbox with a property of the product. I have a textchanged event with
If textbox1.Text <> product.description Then....
but here I get a wavy line under product.description and VS2010 is saying that the object is not defined. Its Dim'd in the page.load so I moved the Dim statement outside the page class so that it will be accessible to all events on the page.
The dim statement is Dim product as New product
In my not ispostback chunk of code I have for example product.ID = 1 which will get all the product properties for product 1
The wavy line has gone but when I run the page all works fine on page load. Data is displayed so my product class is working fine. As soon as I make a change in textbox1 and the event triggers product.description is nothing. It got reinitalised.
How do I stop this from happening...
Your "Product" is not persisted between postbacks.
Only control objects in aspx page are persisted/restored automatically.
To remedy this there are multiple approaches.
If Product is loaded via setting "Product.id=1" then what I woudl do is have a hiddenfield that receives the value of the product.id during prerender event (to save it in the page) and in an init event I would restore the "Product.id=hiddenfield.value" but only when it is a postback to reload your object.
EDIT
Thanks for picking my answer. I'll elaborate a little on the various ways to deal with this and why I suggested my answer.
Store Key in HiddenField Reload from DB:
PROS: Product is always Fresh/Correct/Current values. Corresponding to the database. Databases are very efficient to return a record based on a primary key. Very little data is sent to and posted back from the client browser. Low complexity. Each page opened by the client is safely isolated.
CONS: Multiple database transactions. If the DB is already strained or extremely massive you may need to consider even the smallest efficiency gain, but this is not common or likely on a primary key based record
Session State (store entire object):
PROS: Lowest time to "load" object since it's available in memory already once loaded. Less DB Transactions. No data piggy backed to the client and back again.
CONS: Object can become "out-of-date" if altered in the DB. Users who open multiple pages of your application can end up getting the wrong object if both require a different "Product", so instead to be totally safe you need a more complex structure in place to store more then one product or store them based on some kind of key (such as the product ID). Server Memory is used, if serving thousands of users or your product data is large it can become an issue, especially if you do this in many pages with many objects.
Serialization (store the entire object in the page in a field, similar to event state):
PROS: Once loaded, the Database is accessed only once for a specific product, then the product is held, in it's entirety inside the page, it is recreated by the server from the data in the field or via viewstate. Each page opened by the client is safely isolated. Is fairly easy to implement storing in ViewState of the Page.
CONS: Object can become "out-of-date" if altered in the DB. ALLOT more data is added to your page responce and the users next page request. Is more complex to implement because the object needs to be designed to be serialized correctly. Complex objects require allot of manual code to be serialized successfully.
again, there are many other ways to deal with this, such as storing items in a synclocked dictionary style object global to the application, but is considerablby more and more complex as you go.
This is likely the standard ASP.NET page life cycle problem.
After you initialize the page, it gets sent to the user's browser. When the user clicks on something, the browser sends a postback request back to your application. The view state allows the textbox1 object to remember what was in its Text property. However, your Page_Load ran from scratch, and, yes, everything including your product object got recreated from scratch.
If you want your product object to "remember" what it knew before the postback, you'll have to remind it. One way would be to store the initialized value in Session state, and then refresh your product object during the postback section of the Page_Load method.
Every time you do a postback, you're working with a new instance of your page class. The prior copy of your class was thrown away and probably disposed before your browser even rendered the page to the screen.
If you want to persist a value across http requests (of which postbacks are just one type), then you need to put it somewhere like the Session.

web user control persisting properties (viewstate, session, context) Am I missing something

Maybe someone can help me out. I have created a simple web user control, a date and time picker, to be dropped onto my webform. This all works very nicely, I can set properties, usee the control satisfactorily for ui etc.
When it comes time to "use" the controls selected_date_time property, I just cant get it to persist. Nothing.. I have researched and tried endlessly using viewsate, context and session. Onbiouosly session works, but its dirty, and I am using two copies of this control (start and end time), so session vars really needs to be hacked to maket his work.
Am I missing something? The control gets initialized every time something happens, and obviuosly loses its state information. The ui keeps its state tho, as I can select a date, write that date to a label, and that persists. But when I try to access my properties of the control to retreive the selected combined date and time, (that is already persisting visually), its nothing. I debuggeed and it gets initialized everytime I do any form of post on the page.
Can someone please shed some light on this for me? Its really starting to be an issue now.
Thanks in advance.
Example: (simple components)
UC _ save_method
ViewState("var_time") = "My veiwstate text"
form _read_method
dim str as string = ViewState("var_time")
form sees nothing in the viewstate var.
I have also tried it with normal properties and values, which wasn't working, which is why I moved on to viewsate var's for my properties. Right now, I am just trying to get the viewstate to work even without properties.
Seems my form and the control must have two seperate viewstates? I am a bit of a n00b concerning viewstates.
Thanks
[solution]
You have to explicitly reset your properties on the prerender method of the control. My misunderstanding was that the page and the control share the same single viewstate. Turns out the control and the page that its on, has its own independant viewstates.
So absically, on your property set function in the control, set your value in the viewstate, and upon prerender, take that viewstate value, and set the property get variable =- the value in viewstate.
You can now access the property from your page as if everything was normal and the world is not ending... pheww
Thanks to cnay for directing me.
'Usr control xyz
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
my_time = ViewState("var_time")
'my_time is the get variable for property date_time
End Sub
'page use
xyz.date_time
Perhaps, you should post the complete control code to get the better answer but speaking in general terms - view-state (or control state) is a typically correct approach to persists control state such as properties. Each control instance get the different view-state bag and hence collisions are easily avoided.
Now, coming to your problem, a typical editable control first restores its state from view-state and then uses the request data to modify the state as needed. For example, a simple text-box control would persists its text value in view-state. On post-back, the text value will be restored from the view-state and then gets overwritten by the value present in the request (looked up by UniqueID property).
Now, for user controls, typically you can use child controls values (or properties) to derive the control value/properties - so these may not use view-state. However, if you add properties/state that is not backup by child controls then you may have to back them up in the view-state. So let's say your user control has two child controls - one for Date and other for time then can combine their values to get the selected date-time value for your control.

How to save value across postbacks for a composite control without using viewstate

I have a composite control that has a couple of private fields that reference values in the cache and these private fields are called during the constructor method. Since a string key is used to identify the value in the cache, I must have a way of storing that string key in such a way that it is available at the time the control is instantiated, and I have to be able to reference it on postbacks without it changing.
In addition, this key is generated the first time the control is loaded, but it should not be changed again after that first time.
How can I accomplish this?
I have already tried saving it to viewstate, but that doesn't work because viewstate is not yet available at the time the control is instantiated.
I have tried using a private field and then checking against Page.IsPostback in the constructor and if it isn't postback, I assign a value to the private field, but on subsequent postbacks it looses it's value, and I can't reassign it in the Page.IsPostBack again because it is an autogenerated GUID.
This has got to be something folks have had to do before....
There isn't a lot of state info available during control construction at all, so this could be difficult. Is there some reason you can't move your code which accesses the Cache'ed info into the control's Init event?
I assume you can't use Session because the information stored is related to that specific request/postback. If it's not specific to that request, using Session could be a possibility - but I think you may encounter other problems trying to deal with control state so early in the lifetime.
After seeing your comment to the other answer; you should be able to move your code that checks for the cached datasource into the control's Init or even Load event, so the state will be available.
Also, incidentally; are you sure you really need to cache this data? That could end up taking up a lot of server memory.
Have you tried Session?
You can store anything you like in the session object for one particular user, maintaining the value / object between postbacks.
If you want to store on a global basis and not per ser basis, try Application
Although this isn't the best solution (rearranging your logic to fit the lifecycle model generally is), have you tried accessing the Request directly? I once really wanted to get the selected value off a DropDownList very early in the lifecycle so I could adjust some elements in the building, and I did it like this:
myDropDownList.SelectedValue = Page.Request.Form[myDropDownList.UniqueID];
So instead of waiting for the viewstate to load the server-side proxie's values, I just got it myself from the client-side control value that was passed in on the post. I probably would do things differently if I redesigned that page, but it seems to have worked out alright for now and it solved the problem I was having.

ASP.NET control events exception handling

Suppose I have a button in an aspx page that performs a save of the form data to the database. In the associated event handler, before sending the updates, I read something from a webservice, operation that might result in an exception. In case of an error I want to have an adequate message displayed on the page, and all the data in the form preserved. How can I achieve this? Also, all my pages inherit from a basepage, so I would like, if possible to have all the error handling code in the base class. I do not want, if possible, to surround any web service call with try-catch blocks, I would in case of any unhandled exception to call some method automatically, something like Page_error, but still preserve the data in my forms.
You can easily put a method that manages the display message (maybe setting the text of some errorMessageLabel) in a superclass called from any derived class (if you wanna use inheritance to setup a template for your pages) if an exception is thrown (you can put the call to the superclas method in a catch block if there's actually an exception being thrown or you can manage this manually if the webservice is unavailable depending on your programming style).
As far as preserving the data presented, if viewstate is on and you are not populating your page dynamically then you're ok - if not, you need to explicitly save state information in viewState or session entries and retrieve them back if something goes wrong.
This bit really depends on how your page is actually implemented.

Resources