How to forward data from one page to another - asp.net

I want to take my data tables data to another page. How can I do this? I am programming in ASP.NET.

You can use QueryString to pass data.

If the data is the same on all pages use the Cache. Otherwise retrieve the data again from the database.
Also you can take a look at this article about possible ways of state management in ASP.NET: Nine Options for Managing Persistent User State in Your ASP.NET Application.

You can pass it as a session variable:
Session['yourData'] = dataYouWantToPass;
Then in the next page you retrieve it like so:
var dataYouWantToPass = (YourDataType)Session['yourData'];
In case of string data it would look like this:
//store in session
Session['stringData'] = "Test string data";
//read from session
var stringData= (String)Session['stringData'];

Related

Share data between aspx pages

I need to share data (string, list, array) between two different aspx pages of the same application. What is the best way to do it if I do not want to use cookies and do not want for data to be visible in url.
a) Form post method
b) Session (cookies?)
c) Sql
d) Server.Transfer
Thanks
In-memory Session will be the simplest and quickest (development-wise) to store data between pages without their contents being visible in the query string (URL), like this:
To store a List<string> in Session, do this:
var listOfStrings = new List<string>();
listOfStrings.Add("1");
listOfStrings.Add("2");
listOfStrings.Add("3");
Session["ListOfStrings"] = listOfStrings;
To retrieve the List<string> from Session, do this:
// Check to see if item in Session is actually there or not
if(Session["ListOfStrings"] != null)
{
// Cast the item in Session to a List<T>, because everything in Session is an object
var myListOfStringsRetrieved = Session["ListOfStrings"] as List<string>;
}
Note: I am assuming you use C#, but this can easily be translated to VB.NET.
Some more details might be helpful. What type of information do you want to share? If it is something that needs to be saved, then perhaps it makes most sense to save the data in your database (or local storage, or what ever you are using) from one page and retrieve it in the other. If it's just temporary data, it probably makes more sense to post the data through a form, or use a session variable. The problem with the session variable is that you might time-out your session. A session variable wouldn't be my first choice.

Pass list of ids between forms

I have an ASP.NET c# project.
I have to pass a list of values (id numbers such as "23,4455,21,2,765,...) from one form to another. Since QueryString is not possible because the list could be long, which is the best way to do it?
Thanks in advance.
Thanks for all your answers, you are helping a lot !!!
I decided to do this:
On the first form:
List lRecipients = new List();
.....
Session["Recipients"] = lRecipients;
On the final form:
List lRecipients = (List)Session["Recipients"];
Session.Remove("Recipients");
You could use Session collection.
In the first page, use:
List<int> listOfInts = new List<int>();
...
Session["someKey"] = listOfInts
And in the second page, retrieve it like this:
List<int> listOfInts = Session["someKey"] as List<int>;
If your using asp.net webforms you can put it into a session variable to pass stuff from page to page. You've got to be concise of the potential performance issues of putting lots of stuff into session mind.
Session["ListOfStff"] = "15,25,44.etc";
There are any number of ways to pass this data. Which you choose will depend on your environment.
Session state is useful, but is constrained by the number of concurrent users on the system and the amount of available memory on the server. Consider this when deciding whether or not to use Session state. If you do choose session state for this operation, be sure to remove the data when you're done processing the request.
You could use a hidden input field, with runat="server" applied to it. This will make its data available server-side, and it will only last for the duration of the request. The pros of this technique are that it's accessible to both the server code and the client-side JavaScript. However, it also means that the size of your request is increased, and it may take more work to get the data where you want it (and back out).
Depending on how much data's involved, you could implement a web service to serialize the data to a temporary storage medium (say, a database table), and get back a "request handle." Then, you could pass the request handle on the query string to the next form and it could use the "handle" to fetch the data from your medium.
There are all kinds of different ways to deal with this scenario, but the best choice will depend on your environment, time to develop, and costs.
For Asp.NET MVC you can use ViewData.
ViewData["ID"] = "";

Where to store currently selected item id?

I'm trying to write an asp.net app which searches a sql db and returns/updates the data.
I want to be able to hold the currently selected id of the item my user has selected. For example a doctors surgery would select a patient record then be able to browse the app without having to re-select that patient on each page.
What would be the best way to do this. Ideally I need to be able to get this ID application wide. the only thing i can think of is to create a public class, store the id and make it public but this seems quite messy
Thank you
Store it in a Cookie or a Session variable.
Cookie info
http://msdn.microsoft.com/en-us/library/ms178194.aspx
Session Info
http://msdn.microsoft.com/en-us/library/ms972429.aspx
I would recommend storing it in a session variable:
Page.Session["CurrentPatient"] = YourPatient record
To get the record you would use:
YourPatientRecord = Page.Session["CurrentPatient"] as PatientRecord;
To make things easier I usually create a property in the page or base page to use throughout the system.
eg:
protected PatientRecord CurrentPatient
{
get
{
return Session["CurrentPatient"] as PatientRecord;
}
set
{
Session["CurrentPatient"] = value;
}
}
Then to use it in the page it would simply be:
PatientRecord oPatientRecord = this.CurrentPatient;

What options to I have to pass a value between two asp.net pages

I want to know what the best practice is for passing values (sometimes multiple values) between two asp.net pages
In the past I have used query strings to pass a value in asp like this:
href='<%# Eval("TestID","../Net/TestPage.aspx?TestID={0}") %>'><%#Eval("Title")%> </a>
I assume you can do this in the code behind but I do not know the best way.
I also assume it is possible to pass more than one value.
Could someone provide me with a VB snippet which would give me an idea of how to go about this?
You have many options for passing data and all of them can pass multiple values between pages.
You can use the Request.Form collection to capture values that have been submitted from an HTML form with the POST verb (i.e. " method="POST">).
The code looks something like:
Dim formvalue As String
formValue = Request.Form("FormField1")
You can also use parameters in a URL query string (much like you example):
Dim queryStringValue As String
queryStringValue = Request.QueryString("QueryStringValue1")
You can set a cookie (it's lifetime will depend on the Expiry property value that you set):
Setting a cookie (note: you use the HttpResponse object here. The user's browser stores the cookie when it receives the Set-Cookie HTTP header value from the response to a request)
Response.Cookies("CookieValue") = "My Cookie Data"
Response.Cookies("CookieValue").Expires = DateTime.Now.AddDays(1) ' optional, expires tomorrow
Retrieving a cookie value (we use the HttpRequest object here):
Dim cookieValue As String
cookieValue = Request.Cookies("CookieValue")
You can use the HttpSessionState object (accessible via the Session property of a page). To set a session variable:
Session["SessionValue"] = "My Session Value"
To retrieve a session value:
Dim sessionValue As String
sessionValue = Session["SessionValue"]
There's another way to pass page state between pages using Page.Transfer (see How to: Pass Values Between ASP.NET Web Pages), but I'd try and get comfortable with the above before looking into that.
As far as best practices go it really depends on what data you're passing.
Don't pass sensitive data via URLs (query strings), forms or cookies. These can intercepted in various ways
Pass sensitive data using a server-side store (like session state or a database) but consider how to keep the session ID safe.
Never trust data from outside your application (data that users have entered via a form, information read from a database, etc.). Always encode this information before displaying it again in your pages. This prevents against Cross-Site Scripting (a.k.a XSS) attacks.
Don't use sequential IDs in query strings where you're passing user-specific identifiers between pages. Say you create an Orders.aspx page that lists all orders for a customer. You pass in a CustID parameter via a query string: Orders.aspx?CustID=123. It's easy for someone to change the URL to Orders.aspx?CustID=124 and view information they shouldn't. You can get around this by doing a check that the current user is allowed to see the information, you can use an identfier that can't be easily guessed (commonly a GUID) or pass the information on the server-side.
It would help you to check out the following links:
a. Cross page postbacks
b. How to pass values between ASP.NET pages (MSDN)
c. Another article by Steve C. Orr on Passing values.
You can use a session, cookies, the query string, hidden form fields in a post request.

ASP.NET MVC - Is there a way to simulate a ViewState?

I have the following situation... In a certain View, the user must select the initial hour, the final hour and the weekday. But, I can't save this informations to DB 'cause I need to save my whole page and I need the primary key of the primary table, but that's not the point.
So, while I don't save these data to DB, I'm saving to a Session. I was told to save to a cookie, but it appears that cookies have a size limit. So, I'm saving to a Session.
Buuuut, I was also told that I could save these informations (hours and weekday) to the user page, simulating a ASP.NET ViewState...
Does anyone know how to do this?? Does anyone know how to save temporarily these data withou using cookie or Session??
Thanks!!
Hidden input fields won't help?
<%= Html.Hidden(...) %>
Update (serializing an object to base64):
var formatter = new BinaryFormatter();
var stream = new MemoryStream();
formatter.Serialize(stream, myObject); // myObject should be serializable.
string result = Convert.ToBase64String(stream.ToArray());
When you want to fetch it back:
var formatter = new BinaryFormatter();
var stream = new MemoryStream(Convert.FromBase64String(hiddenFieldValue));
var myObject = (MyObjectType)formatter.Deserialize(stream);
Make sure you validate the data stored in the field when you use it as the client might change it. ViewState takes care of this automatically.
Side note: ASP.NET uses LosFormatter instead of BinaryFormatter to serialize ViewState as it's more efficient or ASCII based serialization. You might want to consider that too.
TempData["MyData"], mind you this will only last one round trip.
You could save a javascript array on the client... and then transmit all the information when the user ultimately saves.
You have to work a little more, but in the end it pays off.
I heavily use jQuery to do stuff like that, it's easier than it seems.
If you just want to save the data for that request and the next request I'd recommend using Tempdata, else I'd recommend using Mehrdad`s answer.

Resources