Passing an object(control) in session from one page to another - asp.net

I need to pass a Infragistics ultrawebtree from a page to another. I used Session("data") for this and then I just access it from another page. But when I assign the session value after casting to a Infragistics ultrawebtree control in my second page, it doesnot build the tree structure and it is invisibile. Is I am wroung in this approach, is there any other way to pass the entire tree structure from one page and display it into another page. Any help is appreciated

If anything, I would store the datasource in session instead of the tree. Storing the entire control in session creates a lot of unnecessary overhead, and limits your options per implementation on the next page.
EDIT: You should be able to export the tree structure to XML format, and store the XML in session. According to the documentation there should be WriteXmlDoc() and WriteXmlString() functions available. There's also ReadXmlDoc() and ReadXmlString() functions you can use to repopulate the tree on the next page.
Here's the documentation for the UltraWebTree. You'll see these methods under the Public Methods section:

Only the data should be stored in session. Storing controls in session is likely to cause issues because the control will be disposed during page unload and controls shouldn't be accessed after being disposed which is what would happen when accessing the control from session. See Why Controls Shouldn't be Stored in Session for more details.

Related

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.

How bindable controls (GridView, Repeater) maintain source data between postbacks

I use GridView & Repeater (and other like DropDownList) controls extensively in my application along with ObjectDataSource components and classes that serve data for ObjectDataSource (TypeName / SelectMethod attributes on ObjectDataSource). I recently noticed that SelectMethod is only called when
IsPostBack == false
Also, when I bind manually, I always bind when !IsPostBack. I never was curious how controls maintain their data between postbacks, until now (I have to create GridView with sorting/pagination etc and I want to do it efficently).
Could you explain / provide some links with descriptions how it's done?
Also I don't get one thing: when working with GridView and I iterate over rows, sometimes I need to access its GridViewRow.DataItem property in order to get backing object (usually to get some kind of ID). And sometimes it's null - sometimes not. I couldn't figure out why. However then it's null, I still can access (for instance) GridViewRow.DataKeys.
Thanks
EDIT: know when answers say that it thanks to ViewState, I have another question: If I data bind 100 business objects which are pretty heavy and I only use a few properties while data binding (let's say I also use OnRowDataBound event to render some additional data), does it mean that whole objects are serialized?
ASP.Net uses ViewState a hidden variable in the all HTML pages to maintain state of a page.
Reasd this for more understanding
http://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&sqi=2&ved=0CFMQFjAB&url=http%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2Fms972976.aspx&ei=UpE0UK3uBsOqrAe94ICwBg&usg=AFQjCNG5ErbrFH0ZYV_WW-jonIl25xEsDQ
They store it in a hidden field on the page called ViewState (or more precisely "__VIEWSTATE"). If you do a View Source on your ASPX page, you'll see it.
You too can store and retrieve state information for your page in the ViewState by accessing the ViewState property of your Page.
I'd start here http://msdn.microsoft.com/en-us/library/ms972976.aspx
So, yes, if you store a large number of large objects, there is a large amount of data being transferred to and fro to the client in the page cycle. Used carefully, Viewstate can be useful, but used carelessly, it can have negative effects.

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.

building dynamic controls on postback (asp.net)

I'm sure this has been answered but I cannot find it...perhaps because the terms are used for so many differing questions...anyway.
how is the best way to store information about building dynamic controls on postback etc in the init event...
e.g. take the classic "questionnaire" scenario...question.aspx?id=1
get the id from the querystring
load the questions from where ever and build controls dynamically,
or dynamically add each question
user control for how ever many
questions etc
page posts back (user presses submit I guess!)
in the init event...where should you have already stored the id to
recreate the question controls?
things i've tried/thought of so far:
I initially stored the value in
viewstate as it's relevant to the
page, but the viewstate value isn't
available in page init (or is it??)
a hidden variable and then accessing the value in the form collection
session - I don't want to use session, seems problematic, e.g. what if the user views two questionnaires?
the querystring again? but that seems too easy to be changed and the dynamic controls just wouldn't make sense...
in the controls themselves? e.g. disregard the questionnaire id all together and simply go off the question id perhaps?? assuming that control ids would be in some format like controlQ# e.g. controlQ1, controlQ2. this means that each question id must be unique
any help/guidance etc much appreciated!!!
The query string will still be available during a postback, so you could take the ID from there.
If you are concerned about users manipulating the query string parameters, then maybe you should add some additional parameters which will allow you to verify the correctness of the query string during a postback. As a simple example, you could add a MD5 hash of the ID parameter and the current session's ID, and recreate/compare that checksum during a postback.
try to create/load the usercontrols in the page OnLoad.
if you want to load inside a usercontrol other usercontrols use the OnInit event.
use the viewstate for the persistence of the information you will need to re-instantiate the usercontrols during the postback. to map the postback data to the controltree you have to ensure that you have the same control-tree. after that mapping you could change your controltree (load some other controls e.g.)
contols-id: yes, you have to give them unique ids, otherwise it will not work. if you store your questions in a database, there should not be any problem to use the database-primary key for this, so name them e.g. question-1, question-2 (the controls)

Data Class in ASP.Net

I am a VB.net winforms programmer attempting to build an ASP.Net app. I use data classes(objects) through reflection in most of my vb projects and was trying to adapt it to ASP.net using the VB code behind. I have a webpage that serves as an add/edit page for contact info. I instatiate my class which grabs the contact data from the data base then I have a process that loops through the controls on the form and matches up with a property in the data class. I can display data no problem. When I edit data and click the submit button my code calls a then loops through the controls on the form again and matches the control to the property of the data class to update the property of the class. However, my data class is no longer valid. I know web programming is different then winforms but I can't seem to get over the hump on this one. Is this the wrong way to go about this? Is my data class only available on the server side? Do I just reinstantiate the initial class and then loop through the propeties and change what the user changed and then call the update method (see redundant)? How can I get data class into a session object (I made an attempt in the past but was under tight deadlines and had to abandon it, maybe I need to revisit it?)?
Thanks
If you decide to keep some of your data in Session, you owe it to yourself to look at this post. Your code will be much cleaner and easier to maintain.
Yes, you need to reload the data class from the database as one option, or use an alternative approach. The reason is web is stateless, so all local variables are destroyed then the server side page unload process occurs. This means that in between requests, you need something to store your data.
You can read/write an object via the Session colleciton, as so:
Session["A"] = myobj;
myobj = (ObjType)Session["A"];
And so session stores an object for a specific user. Alternatively, cache stores application level data, so one instance of an object is available to all users (where session is unique to each user). You can make cache unique to a user by appending a user ID to the cache string.
var o = Cache.Get("A");
if (o != null) { .. }
Cache.Add("A", o, ...);
And so these mechanisms help you temporarily retain data.
You need to save your data class somewhere, usually in a session variable, otherwise it goes away as soon as the page gets sent back the user. Or else you need to recreate the data class again upon posting.

Resources