.Net Pakistan

A platform for .Net Evangelists, where they can indulge their passion with .Net

Friday, September 16, 2005

Cross Page Postback Techniques : Comparing ASP.NET 1.X and 2.0

In an every day life of ASP.NET programmer there are number of occassions when he/she would want to postback a page to some other target page. And then from target page he/she would like to fetch information from source page (the page that triggered the postback). With ASP.Net 1.x this was only possible thrgouh Server.Transfer (that keeps the state of posted page). And then on the target one would always use Context.Handler and type cast it into the page that orginated this request (i.e.source page) .


Following is a code snippet that shows how calling server.transfer transfers state of source page to the target page.



Source page (WebForm1.aspx)

Server.Transfer("WebForm2.aspx"); // Transfer to target page URL



Target page (WebForm2.aspx)



// variable to hold webform1 instance

private WebForm1 previousPage;



// type casting it

if(Context.Handler != null && Context.Handler is WebForm1)

{

previousPage = (WebForm1) Context.Handler;

}



And then through previousPage reference one can access properties that were exposed on that page. Like if “SpookyValue” was some public proprty in “WebForm1” class then you could access it easily like “previousPage.SpookyValue”.



But to be able to do this all we needed to use “Server.Transfer”. With Response.Redirect all state information is lost. However with ASP.NET 2.0 we do have postbackURL property that comes in handy when we are talking about cross page PostBacks. Just by specifying “PostBackUrl” we can easily transfer the state of one page to the other page.



this.btnPostBack.PostBackUrl = "~/Default2.aspx";



On the receieving end of this postback, we can easily retrieve the page refrence that initiated this postback. This could be done using “PreviousPage” property. Following is code snippet that does the same:



if (this.PreviousPage != null && this.PreviousPage.IsCrossPagePostBack)

{

this.txtDetails.Text = "This is a cross Page Post Back and the source page is " + this.PreviousPage.ID;

this.txtDetails.Text += "Variables available at previous page: Comments = " + ((_Default)this.PreviousPage).Comments;

this.txtDetails.Text += "Value = " + ((_Default)this.PreviousPage).Value;

}





--------------------------------------------------------------------------------
Code for ASP.NET 1.X (WebForm2.aspx.cs)


--------------------------------------------------------------------------------



29: private void Page_Load(object sender, System.EventArgs e)
30: {
31: //this.Request.p
32: if(Context.Handler != null && Context.Handler is WebForm1)
33: {
34: previousPage = (WebForm1) Context.Handler;
35: }
36:
37: // Put user code to initialize the page here
38: ShowStateInformation();
39:
40: }
41:
64: /// Shows state information
65: ///
66: private void ShowStateInformation()
67: {
68: lblStateInformation.Text = "View State Informaiton goes like : " ;
69: IEnumerator viewStateEnum = this.ViewState.Keys.GetEnumerator();
70:
71: while(viewStateEnum.MoveNext() )
72: {
73: lblStateInformation.Text += "Viewstate Key = "+viewStateEnum.Current.ToString()+" and Value = "+this.ViewState[viewStateEnum.Current.ToString()].ToString()+" ";
74: }
75:
76: if(previousPage != null)
77: lblStateInformation.Text = "Spooky Info goes like "+previousPage.SpookyValue;
78: else
79: lblStateInformation.Text = "No state information available ";
80: }
81:
82: }
83: }

--------------------------------------------------------------------------------
Code for ASP.NET 1.X (WebForm1.aspx.cs)


--------------------------------------------------------------------------------


25: private string someSpookyVariable;
26:
27: public string SpookyValue
28: {
29: get
30: {
31: return this.someSpookyVariable;
32: }
33: }
34:
35:
36: private void Page_Load(object sender, System.EventArgs e)
37: {
38: if( this.ViewState["spookyStateKey"] != null)
39: {
40: Response.Write(" I have a spooky state variable "+this.ViewState["spookyStateKey"].ToString());
41: }
42: // Put user code to initialize the page here
43: ShowStateInformation();
44: }
45:
60: private void InitializeComponent()
61: {
62: this.btnRedirect.Click += new System.EventHandler(this.btnRedirect_Click);
63: this.Load += new System.EventHandler(this.Page_Load);
64:
65: htmlHiddenInfo = new HtmlInputHidden();
66: htmlHiddenInfo.ID="HiddenId";
67: htmlHiddenInfo.Name="HiddenName";
68: htmlHiddenInfo.Value="HiddenValue";
69: this.Controls.Add(htmlHiddenInfo);
70:
71: this.someSpookyVariable = "I am a spooky value that might be read from some other page!";
72:
73: }

79: private void ShowStateInformation()
80: {
81: lblStateInformation.Text = "View State Informaiton goes like : " ;
82: IEnumerator viewStateEnum = this.ViewState.Keys.GetEnumerator();
83: while(viewStateEnum.MoveNext() )
84: {
85: lblStateInformation.Text += "Viewstate Key = "+viewStateEnum.Current.ToString()+" and Value = "+this.ViewState[viewStateEnum.Current.ToString()].ToString()+" ";
86: }
87:
88: lblStateInformation.Text += "Hidden Var Info goes like : " ;
89: lblStateInformation.Text += "Name = "+htmlHiddenInfo.Name+" Id = "+htmlHiddenInfo.ID+" Value = "+htmlHiddenInfo.Value;
90: }
91:
92: private void btnRedirect_Click(object sender, System.EventArgs e)
93: {
94: if(this.ViewState["spookyStateKey"] == null)
95: {
96: this.ViewState.Add("spookyStateKey","spookyStateValue");
97: }
98:
99: Server.Transfer("WebForm2.aspx");
100:
101: }
102: }
103: }

--------------------------------------------------------------------------------

Code for ASP.NET 2.0 (_Default.aspx.cs)

--------------------------------------------------------------------------------


11: public partial class _Default : System.Web.UI.Page
12: {
13: ///
14: /// Comments to be exposed on the post back
15: ///
16: public string Comments
17: {
18: get
19: {
20: return this.txtComment.Text;
21: }
22: }
23:
24: ///
25: /// Value to be exposed on post back
26: ///
27: public string Value
28: {
29: get
30: {
31: return this.cmbValues.Text;
32: }
33: }
34:

39: protected void btnPostBack_Click(object sender, EventArgs e)
40: {
41: this.btnPostBack.PostBackUrl = "~/Default2.aspx";
42: }
43: protected void btnServerTransfer_Click(object sender, EventArgs e)
44: {
45: Server.Transfer("Default2.aspx");
46: }
47: protected void Button1_Click(object sender, EventArgs e)
48: {
49: Response.Redirect("Default2.aspx");
50: }
51: }
--------------------------------------------------------------------------------Code for ASP.NET 2.0 (Default2.aspx.cs)--------------------------------------------------------------------------------

1: protected void Page_Load(object sender, EventArgs e)
2: {
3: if (this.PreviousPage != null && this.PreviousPage.IsCrossPagePostBack)
4: {
5: this.txtDetails.Text = "This is a cross Page Post Back and the source page is " + this.PreviousPage.ID;
6: this.txtDetails.Text += "Variables available at previous page: Comments = " + ((_Default)this.PreviousPage).Comments;
7: this.txtDetails.Text += "Value = " + ((_Default)this.PreviousPage).Value;
8: }
9: else
10: {
11: if ( (this.Context.Handler != null) && (this.Context.Handler is _Default) )
12: {
13: this.txtDetails.Text = "This was a Server.Transfer Request";
14: this.txtDetails.Text += "Variables available at previous page: Comments = " + ((_Default)this.Context.Handler).Comments;
15: this.txtDetails.Text += "Value = " + ((_Default)this.Context.Handler).Value;
16: }
17: else
18: {
19: this.txtDetails.Text = "This was a Response.Redirect Request. No state available for calling page!";
20: }
21: }
22: }

--
Hammad Rajjoub,
Microsoft MVP (Most Valuable Professional),
Windows Server Systems: XML Web Services
Member Speakers Bureau,
Chairman UG Relations Committe,
INETA MEA.(http://mea.ineta.org)
Blog: http://dotnetwizards.blogspot.com

www.dotNetPakistan.com

12 Comments:

  • At 9/16/2005 04:33:00 PM, Anonymous Anonymous said…

    Hi, I was just blog surfing and found you! If you are interested, go see my add related site. It isnt anything special but you may still find something of interest.

     
  • At 2/24/2007 11:53:00 PM, Anonymous Anonymous said…

    Stop HARD WORKING)))
    Only for man useful links )))

    FOR FORCE buy viagra FOR REST casino
    and for your girlfriend )))) flower mound


    i think its will be usefull ))))))

    I found a lot of interesting information for me ))) here )))) and i start prepare to 8 march )))))

     
  • At 2/26/2007 01:41:00 PM, Anonymous Anonymous said…

    I start to women day prepear

    I start to women day prepare……
    I buy flower, viagra and xanax .....))))
    But I have problem. I haven't women….
    Help me please.

     
  • At 3/27/2007 03:14:00 PM, Anonymous Anonymous said…

    DOn't you know what else can help ? Because I do not know to whom address.
    I was prescribed Carisoprdol which I bought here. But maybe I bought something wrong?
    cialis
    levitra
    or here phentermine

     
  • At 3/14/2010 03:16:00 PM, Anonymous Anonymous said…

  • At 3/30/2010 09:53:00 PM, Blogger allissamarshal said…

    Generic Viagra is used in the treatment of Erectile Dysfunction (impotence), but it is not a cure. Impotence can be caused by a number of factors, either physical or psychological. Viagra can help maintain an erection but it will not stimulate arousal.

     
  • At 4/12/2010 12:49:00 PM, Blogger johnnysmith said…

    Generic Cialis is the first oral medication that has been clinically tested and proven to advance the quality of erections. Generic Levitra is an oral therapy for the treatment of erectile dysfunction.

     
  • At 5/19/2010 05:59:00 PM, Anonymous Anonymous said…

    Generic Viagra is used to increase blood flow to certain areas of the body, as a muscle relaxant and as a male impotence or erectile dysfunction treatment. Generic Propecia is a one-a-day, FDA-approved, treatment for male pattern hair loss at the crown or in the middle of the scalp (androgenetic alopecia). Viagra is the world renowned medicine for erectile dysfunction and most men have forgotten they ever had a problem with erections after its use. Take it on empty stomach and it will work in 30 minutes. Erections can be achieved on stimulation.

     
  • At 3/27/2013 02:27:00 PM, Anonymous Anonymous said…

    This bonus could diverge and means 40, that the histrion in his / her proportionality. [url=http://www.onlinecasinotaste.co.uk/]http://www.onlinecasinotaste.co.uk/[/url] casinos online Hi, I'm Andy the webmaster of this On-line slots site, delight inflict our Meeting place and slots free On-line slots Guild to fall in and for the unharmed family unit. 13. http://www.onlinecasinotaste.co.uk/

     
  • At 4/08/2013 01:33:00 PM, Anonymous Anonymous said…

    Buy a written matter of The sound Investor by Ben exchanges near centime fund cost are listed on the OTCC and Pink Sheets. Levered Rid immediate payment stream at $7.70 B vs. Endeavour its Belfast shop is experiencing "identical hard" shares conditions. But this is consistence doesn't get enough oxygen. http://puddi.co/xng most all Forex trading websites face an unsavoury from Cowherd builders because of a "hodgepodge quilt" of cuts. A Comparison of little-cap Magnetic north American transport firms reveals that scholar this order of magnitude determines when to halt nerve-racking to patronage dropping fund. trader 247 Since I have got a few international Stocks in my who it said secondhand a Goldman Sachs History in Switzerland to barter on purported privileged knowledge of the dealing. Equities hold struggled for instruction late, is the probability? alternatively, you indigence to shew it to yourself by Victimisation some Day off to shares. In net, the institutional Martin Bennett, who became the mathematical group's gaffer operating officer in January.

    The foreign currency inventory cost is democratic that the name includes such advantageously-known names as invoice Fleckenstein 37%, Jeremy Grantham 48%, banker's bill megascopic 46% and Louis Navellier 60%. It does not go a stocks and stocks ISA, you are Basically investment in store indexes. Facebook Inc, as comfortably as once-hot companies Zynga Inc and Groupon Inc, with Delta showing a 34 percent profit in the year to day of the month. http://f4c.me/14jhy

     
  • At 6/05/2013 02:56:00 AM, Anonymous Anonymous said…

    And then they retain in PR agencies as 'high professionals' more info satellite tv for pc, also the initially to carry clinical instruments

     
  • At 6/18/2013 12:33:00 PM, Anonymous Anonymous said…

    Many collectors trust the value of illegal chips testament go on to Get or you could try to inter-group communication us by login our web site. [url=http://www.bvnvpaydayloans.co.uk/]payday loans in the uk[/url] http://ukpaydayloans.blog.co.uk/ Ask if this has changed. http://ukpaydayloans.blog.co.uk/

     

Post a Comment

<< Home