Matt
Matt

Reputation: 26971

Passing an object from one page to another in 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.

Upvotes: 0

Views: 8308

Answers (3)

Freddy
Freddy

Reputation: 3274

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"];

Upvotes: 4

redsquare
redsquare

Reputation: 78667

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.

Upvotes: 0

womp
womp

Reputation: 116977

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;

Upvotes: 1

Related Questions