Passing values between two "totally different" pages - c#

To be clear, the two pages are only logically related in other words the values in my FirstPage.Aspx pass values to my SecondPage.Aspx so it control components and certain attributes of the controls in my SecondPage.Aspx, the SecondPage.Aspx is not a redirect or transfer from FirstPage.Asp. sorry am so sick of reading about all the answers but the one I actually need!
Consider the firstPage contains a textBox which get a value from the user or the web admin to set his preferences about the gridView page size on the SecondPage or a Text property of a label on the SecondPage
I want to explore my options to do so
PS: I was told to use a database to store values from the first page then on the page with my Label for example I connect to the database and retrieve the value and set it to the label...is this a best practice to let the page connect every time it loads to set some values sometimes it's just an int like 5, and most of the time I'd be connecting already to the database to display some table's data in a gridView or any databound control!
EDIT:
Sorry if I was a bit rude, it just hit me that I'm mainly getting the same answer that I read which is totally not my case!..and of course thanks to some of you mentioned the database solution, I hoped I could get an example or an article for my particular case since I think even it's simple but yet it's essential...

ASP.NET framework provides several mechanisms to maintain context that lasts across several HTTP requests. The data you want accessible across calls, can be stored in this context. All you have to do is decide how long do you want this context to be maintained (because it consumes resources), and if you want this context to be available across more than one server.
Application State : Which is maintained for the lifetime of the application i.e. from when the application is first loaded by ASP.NET, till it is unloaded for whatever reason.
Session State : ASP.NET is able to identify a series of HTTP requests emanating from a specific client (IP address), close to each other in time, as a session. It can create a session context that persists across such a session, in which you can store data that is accessible to the calls in the session. The session state can be made available across server boundaries by associating it with a DB or shared memory.
Database
Viewstate : You can use Viewstate to maintain context, but keep in mind that Viewstate is transferred over the wire for every request / response. It has been known to get quite large, specially if you use controls.
Cookies : Again, transferred on the wire for each request / response.

You can use:
Session variable
Cookie
Database value
each one of them have their own pros and cons
If you want the value to be stored the next time they come to page 2, use a database value. if not, use a session variable.
The database value will give you a persistent value, and you can then store other such user variables there.
the session will give persistent data, but only for the browsers current session. The data will be lost if their session times out.
From all you've stated, i would assume a database value.

U can use cookies, session etc but if you want to pass something that defines the whole content of the page, like an ID of some sort, you might just want to put it in the QueryString. (ex: default.aspx?id=4)
Cons: everyone can read (or change) the value, not usable for critical data
Pros: everyone can read the value, and the link can be sent to others

I'd suggest you start here: Get Started with ASP.NET
If I understand your question, you are looking to do Cross Page Posting. If one page isn't posting to a 2nd, you'll need to persist the data somehow (database, session, xml file, etc). But, from reading your question, you sound like you just want to cross page post...

Your question is very confusing, took me a lot of time before I could I understand what you actually need. Since there is no events in HTML, you will need to use JavaScript and some kind of web-service (AJAX).
Page A will store the value in database, and JavaScript on page B will constantly check database for new values, get them and output to the user. In order to that it needs to connect to some webservice/webmethod that will return the value from database to your page. A good example can be found here.
Alternatively you can refresh page every 5 seconds using
<meta HTTP-EQUIV="Refresh" content="5">
and check for the new database value on Page_Load server event.

I think the better answer is "Control State"
Reference : http://www.asp.net/general/videos/how-do-i-use-control-state-to-persist-information-for-a-custom-web-server-control
but I couldn't get this implemented on my case, two different pages
for example : the web user control is placed on News.aspx and the textbox which will have the value to be assigned to the control on News.aspx is placed in myAdmin.aspx page!
and to be honest, I didn't quite understand the code
So! do you think this is the best solution ? if yes do you think It can be used for my case (two different pages) ??

Related

How to handle multiple sessions for same website using same browser with different tabs. ASP.net C#

How to handle multiple sessions for same website using same browser with different tabs. ASP.net C#.
example like google if we open 2 account in same browser it will not effect user details.
All the tabs in a browser share the same session(i.e. identifies to the web server as the same user), this is the default behavior. There are use cases where you would like each tab to connect to the same webserver as different user, this need to be handled via your web application by adding some specific info to the query string in your URL, or hidden form fields, etc., ASP.NET provides cookieless sessions, that can be used for this scenario, see this documentation.
There are other blogs with examples out there that you can follow. One such is this one - shows using a GUID in url route to differentiate different user, and solution to use unique window name and post it back to server using hidden form fields.
Well, as noted, session() is global to the user. In fact, they can launch two different browsers, say FireFox, and Edge - and they will BOTH continue to use the same session values!
What this REALLY means is that from day one, your designs HAVE to make this assumption. If you don't make this simple assumption, then you can be in for a world of BIG hurt if you "just out of the blue" wrote code without the above concept in mind.
In other words, for global things, then session() is fine. However, if you start writing BOATLOADS of code based on using session() to persist values on a SINGLE page? DON'T!!!
And it takes a few seconds in 99% of cases to flip code from session[] to ViewState[] for a given page.
So, now then the ONLY issue is when we use session[] to pass values around from page to page.
Using session() for passing values is ok, but NOT for such information like PK row values such as booking a hotel room, or say selecting a house to buy.
However, like a lot of people, the problem is we don't really think about this issue, or don't know about this issue until it is too late.
So, this is a problem. You want the "easy" of session(), but we need a way to pass around values from page to page.
As noted, one way is to pass values around using parameters in the URL. But then again, that's rather ugly. Sure, for some things like to filter a grid by a given city, then that can be really nice, since then users can save such a URL, or often modify the URL to their liking.
However, for a simple pick of a house or say a hotel room to book, then you can't of course allow or risk doing that (since you would be exposing primary row keys and selection in plain view. Worse yet, it can be a huge security risk. (some very early credit card and other types of sites would actually let you type in values that would let you get and see OTHER USERS information!!!
So, here is how you can handle this issue:
First up, we have these simple choices:
Parameters in URL - they are ugly, high risk, but GREAT for things like city filters etc.
Session() - this is global to the user - includes separate browsers launched.
ViewState - this is per web page - ideal for what we need, and PER PAGE!!!
HiddenFields (in markup) - again, per page - ideal for what we need, but PER PAGE!!!
So, in regards the per page options, only URL parameters can work for passing.
(sans the session() option).
ViewState is great for per page, but you can't use ViewState for passing values between pages. Keep in mind that viewstate is client side, and while encrypted?
Well, for not super high security, then it ok to use. Just remember, ViewState should be kept small, since it goes with EACH button click and PostBack, ViewState becomes part of that "package" and post.
ViewState is part of the page post-back. This is certainly ok, and even better then hidden fields which appear in plain view client side. Just keep in mind ViewState increases the size of each and every post back for a page. So, keep it light, small, and don't persist LARGE amounts of data like say some large dataset.
(unlike Session() which is 100% server side).
So, we need:
Easy approach - per page, but NOT have to re-write a lot of code.
So, while you could say munge up the URL, then they start to look really ugly, and while that might get you a session for the given page, your session() code has to be changed - and it gets messy.
so, just limit using session() to pass values, but NOT persist per page - and you then quite much home free.
In effect? I am saying NEVER use Session to persist values in a page unless you have no other reasonable choice. (use ViewState).
The other issue? What good is to suggest some approach in which you have to re-write a boatload of existing code?
I find that even a page with quite a bit of Session() stuff can in less then a minute be changed over to use ViewState. In fact, you can in most cases use search + replace Session to Viewstate.
So, the only issue left is now the passing of values from page to page.
Use session freely to pass values to the next page. However, for any values that are say PK values, or row identification values, or values that will "break" or "damage" the operations of that page if MORE then one page were to be open? Then simple transfer the values in session to next page AND THEN ALWAYS on FIRST PAGE load (IsPostBack = false), you simple transfer the values to ViewState.
This works really nice, and is BOATLOADS of less work then trying to adopt some silly parameter in the URL or what ever other junk people propose. In other words, we want the LEAST DAMAGE to existing code.
And also, because session() is global? Then it starts to get REALLY messy. I want to say pass 4 values to the next page. And then on that page I might have some more values - all of sudden, while writing code, you can't even remember what session() name to use - and it piles up into a BIG MESS REALLY fast. You wind up with a boatload of session values - ever more growing in your application. It just a mess, and global values tend to be a HUGE mess in any applcation - including that of using session().
And, often, 4-5 values are for the SPECIFIC page - so do NOT create 4-5 session() values, but add a typedef or simple class to the project. And use that for passing of the values. It MUCH LESS clutter in session(), and as you about to see, it also MUCH nicer for transferring these values to Viewstate.
So, we now have this:
we adopt and use View Sate for each page.
we ONLY use session to pass values to next page.
Lets give a simple example.
We say have a grid of hotels - you pick one. As noted, for buying things, picking hotel etc, then passing that value with session is OK AS LONG as you adopt the above rule (that we transfer values to Viewstate in the target page).
The goal here is to allow multiple working tabs or copies of the browser running, and of course minimal code changes.
So, say we have a GridView, and a Hotel to book.
So, note the values we pass (hotel ID, room type, nightly rate).
As noted, we then navigate to the next page (probably additional room details, etc.) - confirm booking etc.
But, as we noted, we can't use session() anymore, since they might have two browsers open. Heck they might have the page open on both their desktop and their smartphone.
So, when we land on the 2nd page, if two pages land using session, we in huge trouble? No, not with our above approach.
So we can still use session() to pass values, BUT we do NOT persist values on that target page. In other words, we break down the two issues:
a) - we using session() to pass values to the next page
b) - we now are NOT using session() to persist values on CURRENT page <<--- this we fix!!!
So, by making our goal here CRYSTAL CLEAR then you as a developer can deal with the above with a SIMPLE change to your existing code. As I stated, you the developer have to code, build, and design your web pages with the above concepts in mind.
So, for persisting values on a given page, just start using ViewState in place of session() - such code will work un-changed in most cases, and all and any values you save ONLY BELONG to the current page.
Only major difference is a user refresh of the page can re-set the ViewState for that page (but session() would and did persist - so some caution is required here - but not much).
So do this:
Pass values by session(), but on FIRST PAGE load (IsPostBack = False), transfer the value(s) to view state, and you are done!!
So, while session() can and is and will be shared between even two browsers running? Well, you click on some row, get PK into session(). Now, say you jump to the next page, on page load (IsPostBack = false), you transfer session value(s) to ViewState, and now you have full operational page - not dependent on Session().
The above is the best solution I have found, and you don't in most cases have to change your code, or introduced some mucked up URL which I find is even more of mess.

How are ViewStates accessible everywhere without being declared?

I was always under the impression that to access a variable in multiple methods, you'd either have to declare it as a class member or pass it in as an argument.
However, I was looking over some sample code recently to learn .NET, and I came across something called a ViewState. I understand it's meant to track some Pages and Control Properties, but I don't understand how it's being used here.
The code looks somewhat like this:
private void RowValidating(object sender, EventArg e) {
ViewState[Backup] = ViewState["TestId"];
// more code that does not include ViewStates
}
private void UpdateBox() {
// some code that does not include ViewStates
int box_id = ViewState[Backup];
// ...
}
How is ViewState accessible everywhere? It is not declared anywhere in the class or in any of the other class files, and this [Backup] key is just sort of created without initializing it. As far as I can tell, ViewState[Backup] does not exist until RowValidating is called.
Would it be possible to set ViewState as a global variable? Or could I always just make my own key that is accessible anywhere? It seems to behave like a dictionary, but I thought the notation was dict.Add(item, value), not dict[item] = value when working with a new item. It must be initialized somewhere, perhaps in some imported library?
Both Session() and ViewState are and can be used to persist values in your code. You don't have to declare them, they are built in features of asp.net
Session() is per user and thus is often used to persist values or even pass values between pages. However in some cases ViewState is preferable.
So for example if you have a productID or maybe even a house you are about to buy? Well, if you have two tabs open or even two different browsers open then Session() applies to all instances of the browser(s) in question open. So if a user has two seperate browsers opened, then the "ID" value you persist in session() will apply to both (so, be carefull, which house ID are you about to buy when you have 3 browser pages open to 3 differnt houses open? So session() is global to the user.
So for say "persisting" a row of data to pass to the next web page/form, Session() can be great - but keep in mind it is shared among all pages opened and in operation by that user. So session() is still per user - but global to that user.
Session() can be server "in memory" (the default). However, if you are using a server farm, then each of those multiple servers can't share their memory, and as such you have to adopt what is called SQL server based session. So in place of holding these values in memory, the session() state is shuffled from a serialized "blob" stored in SQL server. So if you hosting your site say on a cloud based system like Azure (as opposed to regular hosting), then session() can't persist on these so called "large services" based systems (or you are using a server farm with load balancing in which you have multiple-servers hosting the site for scalability reasons). Since multiple copies of the hosted web site can exist at the same time, then a means to have a common session() is required (so they shove a blob thing into SQL server). So you can still use session(), but it actually stored in sql server. It is noted that in some cases session() based on SQL server can cost performance. As high as 10% - perhaps a bit more. I find that in most cases you not notice this performance hit. But it works seamless() and in fact adopting SQL server based session will mean that session() is not frequent lost due to site execution errors. I had all kinds of issues with a site losing session(). If the web hosting and management system puts the server to sleep, or even .net code errors occur, it can (and will!!) often cause a application pool re-start - and that blows out session() (but not with SQL server based ones - they are rock solid).
ViewState is often preferred since it is by EACH NEW web page. And this is stored 100% in the browser. So to persist that houseID or product you about to purchase, then this occurs by page, and not all web pages in use by the user (so in this case, VieweState would be a far better choice). ViewState is thus stored by the browser and is much the SAME mechanisum used when you enter bunch of values in text boxes, and then do a post back. The web page travels up to server - page is processed and sent back down. But you will notice that MOST controls on the page retain their value. To achieve this then ViewState is used. And this applies to hidden text boxes (or hidden fields - much the same as a hidden text box). So this encrypted blob lives in the browser client side. And this blob thing thus goes along for the post-backs and round trips to keep those controls values in-tact.
So you can use session(), or ViewState But, as noted, you don't want to stuff too much into that ViewState, since it becomes part of that round trip life cycle. But ViewState as noted is often preferred since it is per page operation. However, since each new browser page opened creates a new local per page ViewState? Then ViewState can't as a general rule be used to pass values between web pages like Session() can.
However, you CAN pass all values of all controls to the next page. You can do this by using the post-back URL of a button. When you do this, then on FIRST page load, you can use the page.previous property in the on-load event. This will give you use of ALL values from the previous page - and you don't need Session() to do this. You can also use page.Previous if you do a server.TransferRequest as opposed to a Response.Redirect().
Last but not least? You see a lot of sites have a whole bunch of parameters in the URL. So this is often used and has a long history of use. Of course users can mess and change with these values - but they are still often used and often make the URL's rather ugly. For this reason I do like asp.net sites, since then URL's don't expose a bunch of stuff in the URL as parameters and keeps such information out of site and mind. You see a lot of shopping site still using parameters and values in the URL - and they do this for reasons of scalability - (they don't have to store the persisting values server side - it saves resources).

If we have more than 1 page to get details of users then how to handle user's data till last submit

I have 3 pages to get details of user and I'm confused what to do with users' temp data
whether
store in database and delete incomplete form data using scheduler
store in session for that user
store in cookies
All of the options you mention are valid in some cases.
I would not go for the cookies option since they are sent along with every request and the data could get too large.
If you want to keep information over sessions the database is your only option. Else wise choose the option you seem best.
It depends upon the requirement. The easiest will be session since clearing the data is not required .net will do it automatically on session-expire.
storing in database and cookie will result in more code. If you want to use the best option go for cookie it will use the least server resources, but the round trip can be costly if there are many cookies. since cookies also get transmitted every time u make a request.
The other options that you can think of is using the view state to persist the data. It will require the most code to accomplish, but will be the best since the data is only be kept till the user is completing the form. you will have to take one page data and pass it to another page in view state and so on.
1.if you use database then this option requires DB trips that is not good and it also effects to your application performance.
2.Session will be the best option to store user Temp data.With sessions you can use datatable object and then this datatable is assigned to session variable.
3.it creates a problem if some user disable browser's cookies.
Happy coding....

Persist List of Objects Between Pages - ASP MVC

C# - ASP MVC - .NET 4.5 - Bootstrap - Razor
I have a form wizard (http://vadimg.com/twitter-bootstrap-wizard-example/examples/basic.html) that is used to setup a complex object (obj1). A property of obj1 is a List<obj2>. On one step of the wizard I want to add multiple obj2's to the list. Since obj2 is slightly complex as well, I thought I would use another wizard to help build it. Except I need to persist this List<obj2> on wizard 1, while I'm off in wizard 2 building another obj2.
My first thought was to use a session to hold the List<obj2>, I was just wondering if that's a good option, or if there would be a better one? The user may leave from Wizard1 to go to Wizard2 and come back multiple times.
There's no perfect answer here; each approach has trade-offs. But here are some options that I can think of (and these are independent of ASP.NET/C#)
Session (as you suggest)
This will store data in web server memory (by default). If you have a lot of users, this could be a problem.
You risk the information being lost when the user gets a new cookie/the session times out.
Potentially better performance that a db, depending again on the number of users
Database (as you mentioned)
Could cause more database traffic.
Can save information for user even if they close a browser, switch computer, the power goes out, etc.
Maybe a separate NoSQL database just for transient wizard data would be worth trying.
Cookie (store data on the user's computer)
Users can potentially tamper with/view the data
There is a limit on cookie size (4 KB each?)
Local storage (HTML5)
Similar to cookies
But not such a small limit
Not every browser supports it (may need polyfill)
Form/Post/Hidden/ViewState
You could just post the data and drag the information from response to response
But this gets really annoying with back buttons & timeouts
Lots of work, and again, the user can tamper with the information

How to store user entered values across a website using C#?

I am currently working on a website that will have a high volume of traffic on it. The website has only 4-5 pages on it but I need to pass values selected on page 1 over to page 2 where more values are stored and so on until the user gets to page 5 where all values are passed to a third party system using XML.
Currently I use a dictionary object with roughly 20 keys stored in a single session object to hold the values across the different pages. I do this because some of the values are not just simple values like 'name' or 'age' values but can be complex like holding a dataset of results from an XML call on page 2.
I have read everywhere that global variables are bad so I am wondering if there is an alternative to using Sessions for this example? I cannot use a database to hold these values because of the way some of the values need to be stored (i.e. my variables are not just strings/ints). If I was to use global static variables how could I ensure the global variables are unique for each user?
Thanks for your thoughts.
Rich
** Edit 1 **
I am storing the current sessions in ASP.NET Session State and not inproc. I am just trying to figure out if what I am doing is bad practice or just generally accepted as an ok way of doing things. For example on the second page I get a XML result that I store as a dataset in my session for use on page 3/4 of my site. Should I be store/passing this info another way?
I cannot use a database to hold these
values because of the way some of the
values need to be stored (i.e. my
variables are not just strings/ints).
You actually can. You can serialise you object graph and store it as binary column in the database.
Additionally you can have this functionality out of the box and still using SessionState.
Here is an article on how to Store Session State in Sql Server.
So I would recommend to use Session but store the session state in the database.
Sessions are the right choice. The "global variables are bad" argument is a good one, but it's describing global variables, not session variables and pertains to how you organize data being passed among methods within your application. Storing data between pages can be done in only one of three ways:
Store the data in hidden fields or cookies (so everything gets passed back and forth for each page request). You could do this by just serializing your XML and other fancy data, but it sounds like a terrible idea.
Store the data in a database, flat file. This is a fine idea, but you'd still have to do the serializing work yourself.
Store the data in a session. This is exactly the same as option #2, except that C# is doing the serializing for you, and then saving the results in a flat file.
You do not have to do any work to separate the data of one user from another. Every visitor gets a unique session, and the data you store there won't ever be applied to another user (excluding a malicious attack such as a hijacked session).
I would think session is the appropriate place to put things that are relevant to your 'session'. It is true that over-using/abusing session can bite you with excessive memory consumption, but the alternatives can be a bit slower, just depending. Also, if you use SessionStateService or store the Session in SQL Server, you have slow-down in serializing/deserializing the session objects on each request.
You can use ViewState, but that means all of the data will get serialized to the HTTP Form, which means it will get passed back and forth on subsequent requests. Also, I think ViewState gets dropped from one ASP.NET form to the next, so unless you are on the same form, that won't work.
You can store the data in the database. One way is to have Session use SQL Server. If I were to use a database for this problem, I don't think I would use session in SQL Server though simply because if you store it yourself, then you could recover previously entered data.

Categories