8 Jul
2005

Object Oriented Page Redirection

This is a blatant ripoff of the show
notes
of the awesome podcast from Craig at the Polymorphic Podcast.  I am
going to replicate some of his post here to talk about it in a different way. 
Thank you, Craig for the idea in the first place.

Basically, what Craig is right about is this:

This Sucks

There is no type safety in doing this and what if the parameters change to
the page because it is in development?  This happens to me all the time.

private void btnChangePages_Click(object sender,
EventArgs e)
{
    string userId = textBox.Text;
    Response.Redirect(“Destination.aspx?uid=” + userId);
}

This Rocks

Encapsulate
the knowledge of how to get to the page in the page itself.  This allows strongly
typing the command line arguments to this page, also allowing for acceptable overload
scenarios.

public class Destination
: System.Web.UI.Page
{
   public static void GetPage(int userId)
   {
      HttpContext.Current.Response.Redirect(“Destination.aspx?userId=” + userId);
   }

   public static void GetPage(int userId, string name
)
   {
      HttpContext.Current.Response.Redirect(“Destination.aspx?userId=” + userId + “&name=” + name
);
   }
}

Now
just call the page in a strongly typed way in order to feed the page with the overload
that we want.

private
void btnChangePages_Click(object sender,
EventArgs e)
{
   string userId = textBox.Text;
   Destination.GetPage(userId);
}>
>>

 

What Could Be Better?

As we all know, you should NEVER inherit from Page.  You should have a base class
that inherits from Page for all of your custom pages.  Now how can we add
a signature to our base class that forces our pages to implement this technique? 
Since the params are different per page and per overload, the only thing I could come
up with was having your base class implement the method with a parameter array or
Hashtable as the function argument.

Neither of these scenarios are acceptable because we lose the strong typing that we
wanted in the first place.  Any ideas?