Retrieving object List in Asp.net - c#

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

Related

pass C# object between aspx pages

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.

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.

Simple question, retrieving an updated collection of nhibernate objects from the parent

I have a pretty easy question regarding nHibernate but I couldn't really find an answer on google.
Let's say I have a mapped Member object that holds a 1:n foreign key to Mail objects. I would like to retrieve the current collection of mail items for a user when he enters his inbox. If I call memberInstance.Mail (of type IList<\Mail>) it brings back the mail collection but doesn't reflect the new mail that was added since the memberInstance is saved in the cache during login and doesn't make a round trip to the database. If I create a RetrieveMailForUser method, pass it a Member instance and then call code such as Session.CreateCriteria<Mail> I get the current mail for any given member and everything but it seems extraneous to have a Mail collection on the Member variable if I never use it as well as having a collection in the member var that isn't up to date. I could refresh the member every time the user checks his inbox and save it to the cache but this seems to have a lot of overhead. I feel like I'm missing some basic principal of nHibernate. Please help. Thanks!
Code that calls the member:
public static Member GetLoggedInUser()
{
var member = (Member) HttpContext.Current.Session[SESSION_NAME];
if(member != null &&
!NHibernateSessionManager.IsEntityAttachedToCurrentSession(member))
NHibernateSessionManager.AttachEntityToSession(member);
return member;
}
E
from your post I derive two contradicting requirements:
You want an object (Member) in the cache, which should not be updated according to what happens in the database. It is in the very nature of a cache NOT to automatically reload anything or trying to attempt to do so.
You want Mails in the Mails collection of the Member object to be updated whenever accessed (and therefore disregarding what was in the cache at the moment of retrieving the Member object for the first time).
If you want to stick to the first approach, you must update the Member object in the cache directly whenever a new Mail is created for that object (calling member.AddMail(mail) or something like that). I don't know whether that is feasible, since you apparently keep Member in the session, and that would require accessing Member objects of another session.
If you also want 'up to date' list of mails, I guess there is no way around either re-loading your mail list explicitly, reloading your entire object, or just loading the mails in the way you suggested it above already (RetrieveMailForUser). In that case, you can confidently remove the Mails collection in the Member object. You don't have to map collections if you don't need them.

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?

Categories