Monday, December 24, 2012

Server.Transfer has a preserveForm parameter that is not trivial methinks.

preserveForm is the second parameter in a Server.Transfer call and it is pretty important. I think the code I gave here is pretty bad and should really look like this (note the true value in black for passing the HttpContext variables):

HttpContext CurrContext = HttpContext.Current;
CurrContext.Items.Add("q", q.Value);
Server.Transfer("/search/default.aspx",
true);

 
 

...cannot be like so which won't fly...

Server.Transfer("/search/default.aspx?q=" + q.Value, true);

 
 

Fish variables back out on the other side of the leap like so:

HttpContext CurrContext = HttpContext.Current;
var whatever = CurrContext.Items["q"].ToString()

 
 

While we are at it, here is the same thing in VB (per this):

Dim context As HttpContext = HttpContext.Current
context.Items.Add("q", q.Value)
Server.Transfer("/search/default.aspx",
True)

 
 

Go fishing for the variables in VB:

Dim context As HttpContext = HttpContext.Current
If Not context.Items("q") Is Nothing Then
   Dim q As String = CType(context.Items("q"), String)
End If

 
 

This also shows off VB script object-to-string casting and some if logic. (I've been doing some VB script lately in plumbing in old code.) preserveForm should be true to "preserve the QueryString and Form collections" according to this Visual Studio intellisense helper, so I am betting I need it to preserve the HttpContext I just created.

Share photos on twitter with Twitpic

No comments:

Post a Comment