pass C# object between aspx pages - c#

I am creating an ASPX application that collects data from the user can creates a file based on this data. Different types of data are collected based on the type of user. Also, I have to check the database to see if there is data already in the database. I am looking for an easy way to keep track of the data while traversing between all the ASPX pages that are collecting data. I know i can pass the data in the URL and if i don't find an alternative method then i will use that.
My question is, is it possible put the data into a C# object and somehow pass the instance of that object between ASPX pages?

The simplest is to use the Session bag.
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;
When retrieving an object from session state, cast it to the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];
Here's a more exhaustive article on Session state on MSDN: http://msdn.microsoft.com/en-us/library/ms178581.aspx (from which the brief code examples are shamelessly copied)

Assuming the data is not prohibitively big, I'd put the data in Session and retrieve it from page to page.

You can use Session object for this.

Related

Retrieving object List in Asp.net

I have a list of class object that I created as a variable in my deafault.aspx.cs page
List<BoldGauge> boldGauges = new List<BoldGauge>();
I create my object in nessacary function and then add the newly created object to the list so I can retrieve it later as needed.
When I attempt loop through the object later the boldGagues count = 0. I assume I need to either add the List to a session variable or session state.
Does anyone know the best approach for this? There could be numerous different types of controls in multiple lists, so if someone could please recommend an approach that is least expensive, and efficient I would appreciate it.
To persist the list across postbacks, you'll need to store the list somewhere.
You can store it in the Session, but a more applicable place might be the ViewState.
ViewState.Add("GaugesList", boldGauges);
then get it back later
List<BoldGauges> boldGauges = ViewState["GaugesList"];
Note that this is scoped to the page, so if you need the list across pages, use the Session.
foreach(var boldGaug in boldGauges)
{
//do something..
}

ASP.NET Control visibility dilemma

I've got a Page, a GridView using an ObjectDataSource with a SelectMethod and a DropDownList. The SelectMethod, among other things, gets a string-array containing several IDs (to filter the Data) - but I also need it as DataSource for the DropDownList.
Alas, I cannot DataBind the DropDownList inside the SelectMethod since it's null.
An Idea would be to bind this string[] to a Session-Variable, but then I'd have to either re-set it upon every Page_Load or remove it from Session on every other page if I want it to update in case something on the Database changed.
What I'm looking for is some kind of variable that is available both in Page_Load and my ObjectDataSources SelectMethod, but that removes itself upon leaving the page (i.e. navigating to any other page on my Web-Application (preferably without having to call a method on EVERY other Page).
I hope you could understand my problem.
Thanks,
Dennis
As I understand the need to fetch the string array arises from the performance hit that a separate roundtrip will cause. To work around this you may create a separate object to feed your object data source. This object will have two methods one for getting the string array and another for getting the data for the grid (i.e. the select method)
You may then put an object like this in your page and fetch the data in it in a lazy manner. If the object makes a call for any of the data it stores the other part in a field. You can then use the ObjectDataSource ObjectCreating event to pass this object on your page to the ObjectDataSource
protected void odsSomething_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = YourInsntanceAlreadyInThePage;
}
This way you will avoid the roundtrip.
Also consider making two web service calls at the same time using the asynchronous client calls so that you can make both calls for the same time. If this is viable depends on the flow of your logic.
What I'm looking for is some kind of variable that is available both in Page_Load and my ObjectDataSource's SelectMethod, but that removes itself upon leaving the page (i.e. navigating to any other page on my Web-Application (preferably without having to call a method on EVERY other Page).
In a similar situation, I've used the Items property of the current HttpContext. It's an IDictionary (non-generic), so can hold arbitrary objects keyed by arbitrary objects, and its lifetime is precisely the duration of the current request, so will go away as soon as the request is ended. To use:
// Where you first get the data
HttpContext.Current.Items["SomeKey"] = new [] { "string1", "string2" };
// Where you want to to use the data
var strings = (string[])HttpContext.Current.Items["SomeKey"];

How to retain the value of a global variable List<object> after postbacks

I have looked at this question first: retain value after page refresh. But it seems like it doesn't work with collections because the ViewState only store one value. I need to use the collection because I do not know how many instances of object the user will create. Therefore, the ViewState is not an option. I also tried using static variables but it stores the values for longer than I need it (I found the explanation for this here: http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/3664cd62-46c7-4098-88a7-c09647673096).
I would massively appreciate your help.
Often using Session state is better for lare objects, but you can store any serializable objects in the ViewState too ( http://msdn.microsoft.com/en-us/library/ms972976.aspx ).
Note: please avoid using storing data in static properties in ASP.Net as the values are shared across all requests. Note on note - HttpContext.Current is not really static objects (per-request object).
You could store the List<> instance in the client session on the server side. Then on each request you will have access to the list in the session.
However, you should still be able to use viewstate, as long as the items in your List<> are serializable.
You should consider the amount of data being exchanged between the browser and web server when using viewstate. If your items are not unreasonably large and you will not have too many of them in the list then viewstate might not be unreasonable.
The code might look something like this.
private ArrayList GlobalList
{
get
{
return ViewState["GlobalList"];
}
set
{
ViewState["GlobalList"] = value;
}
}
you can use class level variable which hold the value after post if you want to use List make it class level variable then it wont loose the value.

Where and which data to save into session on an ASP.NET MVC 2 application?

I am having some trouble saving the state of my current view.
Currenly I have several selectlist calling their own Action method on the controller that returns the Index view with the filtered model based on the values of the selectlist.
I have also written a little FileResult action that creates a csv file based on the current model. But I am only covering one selectlist right now as I only save the value of selectList1 into the session and access it with Session["SelectListValue1"]
What are the best practices in this situation?
Should I redo the entire (each action for each SelectList) part?
Should I save each SelectLists value into the session and check if it's null?
Or should I just save the Lambda Expression into the session and modify it during every call?
Well, generally in MVC we don't directly save to Session, it's not considered a best practice b/c of impact to your app's performance. Generally, it's a best practice to make each request as stateless as possible.
Each form should follow the POST-Request-GET pattern where possible, so you're not going to do what you did in WebForms as a rule (where you keep posting back to the same form/action).
So you should consider what the state is that you're trying to capture represents. THe list of possible values is one thing, drawn possibly from a database and stored as a list or enumerable in the cache perhaps (in some scenarios; could look it up every time in others). The value that's selected probably represents a property on osme other object, though, so you should use that as your means of getting out the selected value.
If it's something that's not a part of a persistent object, then you can either just read the post values each time and set the viewstate again (probably the best practice) or, if you need to persist that value across a redirect, then use the TempData bag (which works much like session; in fact uses session under the hood) but values get garbage collected after one the next request, so you don't have to worry as much about the memory bloat.
It doesn't sounds like you need to be using the session at all. Can't you pass the values of your select lists via the query string or in a form?

Alternative to Query Strings to Pass Data Between ASP.Net Pages?

I am currently using a number of query string parameters to pass some data from one page to a second page (the parameters hold confirmation/error messages to display in the second page), that due to a third party product can no longer work correctly in the production environment. The user completes an action on the first page, and is then transferred to the second page. What are the possible alternatives to use instead of a query string and GET - session variables, POST data, or something completely different?
Thanks, MagicAndi.
You could create public properties in a source page and access the property values in the target page when using a server transfer. You could also get control information in the target page from controls in the source page by referencing the Page.PreviousPage property.
Both of these methods are oulined here: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
Both POST data and session variables would work just fine. POST data has the drawback that it can be changed by the client and session variables take up memory, so you can choose based on that. I personally don't think that you should pass such messages to the client for the reason stated above but I guess you are already doing that, so...
you can use this if you use window.open("openTheotherPage",...etc)
so form the opened page you can do something like this
var valuefromCallerPage = window.opener.document.FormNmae.textbox.value
or button or anything on the caller page

Categories