Passing an object from one page to another in ASP.NET - asp.net

On page1.aspx I have a button tied to a buttonOnClick event in my server side.
Clicking the button runs buttonOnClick method which generates an object (local to buttonOnclick method) with data I would like to use in the construction of a new page.
Basically, I want to open a new (different) page (page2.aspx) in a new tab, but as this page loads, I want it to render based on the contents of the object generated during buttonOnClick.
How one might go about this properly? Up until now I have been passing URL arguments to the new popup (page2.aspx) and I have it build the object, but I would rather do this properly and generate it buttonOnclick and then load page2.aspx in a popup based on what is the object built in the buttonOnclick method.

Store the object in your Session on the first page and then retrieve it on your second page.
On first page:
Session["myobject"] = myObject;
On second page:
MyObject object = (MyObject) Session["myobject"];

The easiest thing to do would be to store the object in the user's Session.
Session["myObject"] = myObject;
To get it out, you will need to cast it back to the type of MyObject, since the Session cache is simply a hashtable of objects.
if (Session["myObject"] != null)
{
MyObject myobj = (MyObject)Session["myObject"];
}
You can access it from both pages this way. Generally, if multiple pages are going to be accessing the same object in Session, I usually store the name of the session key in a centralized location so that it only has to be updated once should you ever decide to change it. Usually I add a resource file to my application and put it in the Properties folder, so I can use it this way:
string key = WebApplication1.Properties.MyObjectSessionKey;
Session[key] = myObject;

Use session state or store the object in a database and pass the id to the second page. The object will need to be serializable for this.

Related

Passing parameters to new page in asp.net (in Redirecting)

I want to fill Listview in Asp.net with Records which should have link to another page . so when user clicks on one record, they will redirect to new page related to that record.I have many parameters want to keep.
In page Redirecting, is there any other way to passing parameters except with "QueryString"?
You can use Cookies
SET :
HttpCookie cookieName = new HttpCookie("Name");
cookieName.Value = "SarahN";
GET :
string name = Request.Cookies["Name"].Value;
OR you can use
Application Variables
SET :
Application["Name"] = "SarahN";
GET :
string Name = Application["Name"].ToString();
OR you can use the Context object
Passing value through context object is another widely used method.
MyForm1.aspx.cs
TextBox1.Text = this.Context.Items["Parameter"].ToString();
MyForm2.aspx.cs
this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer("MyForm2.aspx", true);
From MSDN
Context
The Context object holds data for a single user, for a single
request, and it is only persisted for the duration of the request. The
Context container can hold large amounts of data, but typically it is
used to hold small pieces of data because it is often implemented for
every request through a handler in the global.asax. The Context
container (accessible from the Page object or using
System.Web.HttpContext.Current) is provided to hold values that need
to be passed between different HttpModules and HttpHandlers. It can
also be used to hold information that is relevant for an entire
request. For example, the IBuySpy portal stuffs some configuration
information into this container during the Application_BeginRequest
event handler in the global.asax. Note that this only applies during
the current request; if you need something that will still be around
for the next request, consider using ViewState. Setting and getting
data from the Context collection uses syntax identical to what you
have already seen with other collection objects, like the Application,
Session, and Cache. Two simple examples are shown here:
// Add item to
Context Context.Items["myKey"] = myValue;
// Read an item from the
Context Response.Write(Context["myKey"]);
You can also refer:
ASP.NET State Management Overview
How to: Pass Values Between ASP.NET Web Forms Pages

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.

How do I create and populate a Plone object in the portal_factory?

I need to create an (archetypes) object from a View of a second object (object2 - which is not the parent of the new object). It needs to be prepopulated with data from the Request, and from object2.
The simple solution would seem to be to use "default_method" on the schema fields, and that can work for the data from the Request, but I don't believe I have access to the View from there, and therefore not to object2, either. In any case, one of the fields is a ReferenceField to object2 and I've read that ReferenceField ignores "default_method".
The other option is to create it inside the portal_factory, set its defaults, and then display the Add page, allowing the user to modify the content as required, or to exit without actually creating the object. Perfect, except that, of the multitude of methods available to create an object, (invokeFactory(), _createObjectByType(), _constructInstance() & createObject(), that I know of), only createObject actually leaves the object in the portal_factory - and since it only returns a string (the URL of the object's Add page), won't accept keyword arguments, and doesn't seem to notify any events (certainly not IObjectCreatedEvent), I can't see how to modify that with my data before directing the user to the edit page.
This is the pattern that I recommend when is not possible to use createObject:
_id = self.context.generateUniqueId("Document")
_id = self.context.invokeFactory(type_name=type_name, id=_id)
ob = self.context[_id]
ob.edit(
description = "text...",
subject = ('tag1', 'tag2'),
title = "some title...",
)
ob._renameAfterCreation(check_auto_id=True)
_id = ob.getId()
Doh. Finally figured it out.
createObject doesn't, in any real sense, create an object. It really is just a URL to the creation form.
Call .createObject(), get the URL for the form, attach the values you want as query parameters:
url = folder.createObject(type_name='xxx')
url += ?title=abc&description=def...'
self.request.RESPONSE.redirect(url)
will do it.

send object from page to page in asp.net

how can i send object from page to page in asp.net?
Have you thought about using a Session variable? You can save your object to a session varible and then retrieve it from the called page.
Here's an example:
Set from one page
Session["myobject"] = MyObject;
Retrieve from another
MyObject o = Session["myobject"]
You can use the Session to store a user-specific object between pages, or send data via a form GET or POST. There is also PreviousPage for a cross-page postback.
Session
Database
Context Cache
XML/Text File
Post/Get
Azure
Querystring
Pure willpower ;)

ASP.NET: How to redirect, prefilling form data?

i want a handler to redirect to a web-forms page, pre-filling in the values of some controls on the form.
i tried setting my current Request.Form data:
if (theyWantToDoSomething)
{
//pre-fill form values
context.Request.Form["TextBox1"] = "test";
context.Request.Form["ComboBox1"] = "test 2";
context.Request.Form["TextBox2"] = GetTheTextForTheThing();
//tell the client to go there
context.Response.Redirect("~/SomeWebForm.aspx");
return;
}
But i get an exception that Form values are read only.
What would be a way to send the client to another page, pre-filling form data?
Answer
i used the Session state to store values. It's important to note that by default a Handler doesn't have access to Session (the Session object will be null). You have to tell IIS to give you the Session object by adding the IRequiresSessionState marker interface to your handler class:
public class Handler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
...
if (theyWantToDoSomething)
{
//pre-fill form values
context.Session["thing1"] = "test";
context.Session["thing2"] = "test 2";
context.Session["thing3"] = GetTheTextForTheThing();
//tell the client to go there
context.Response.Redirect("~/SomeWebForm.aspx");
return; //not strictly needed, since Redirect ends processing
}
...
}
}
You can only populate your Response, the Request is input data and is indeed read-only.
If you are using ASP.NET, there are a variety of ways you could accomplish what you need:
The best way would probably be to pass the data you need to be pre-populated to SomeWebForm.aspx via the Session object, and on that pages Load method, populate your form. Keep in mind that when you do Response.Redirect, a 302 response is sent to the client with the URL the client should redirect to. The process is transparent to the user...but there is a full round trip involved.
Another alternative to populating the users Session would be to add GET parameters via a query string to the redirect to SomeWebForm.aspx.
If you need to transfer processing to the SomeWebForm.aspx page without round tripping, you could use Server.Transfer. This will transfer execution from the current page to the page you choose...however, this can cause some odd behavior on the client end because the URL does not update. As far as the user is concerned, it will still appear as though they are on the same page they started on.
A few ideas that might get you started:
Pass the values in the query string
Store the values in the session state or in a seperate cookie
Store the values in HttpContext.Items and use Server.Transfer instead of Response.Redirect
Another approach that hasn't been mentioned yet is using Server.Transfer makes it possible to use the Page.PreviousPage property, allowing access to the controls on the page that transferred control.
As jrista mentioned though, using Transfer doesn't update the URL shown to the user, which may or may not be an issue. For example, a user can't precisely bookmark a page they got transferred to since the URL will be that of the original transferring page.

Resources