Friday, June 10, 2011

URL Routing in ASP-NET 4 Web Forms


We have experienced this scenario in our daily browsing routine where URL takes a smarter look that can easily be remembered, look simple and yes SEO friendly. This technique is referred as URL-Rewriting in general. So what is URL Routing?

This is a term coined my Microsoft Web development team and was first introduced with ASP.NET 3.5 SP1, where MVC took advantage of routing. Now with framework 4.0 we can leverage this handy tool in web form situations.

There is hardly any difference in URL routing and rewriting in terms of results. Rewriting previously was done through third party dlls and sort of un-managed code (not handled by ASP.NET engine itself).

Making things happen in ASP.NEt 4.0 is super easy, you just have to make some additions in Global.asax file and you are done.

1. Call a function from Application_Start void Application_Start (object sender, EventArgs e)
// Code that runs on application startup
RegisterRoutes(RouteTable.Routes);
2. Create a method and add routes as required void RegisterRoutes(RouteCollection routes)
{routes.Add(new Route("{resource}.axd/{*pathInfo}", new StopRoutingHandler())); // line 1
routes.MapPageRoute ("category-route",
"{name}", "~/gamecategory.aspx"); // line 2
Line 2 is the main thing that adds a route and handles the incoming request for a URL that may be like http://www.yoursite.com/new
First parameter is the friendly name of route that can be used later for getting the outgoing URL and second parameter defines the URL format to match. The third parameter defines the actual page that will handle the request in the background. The MapPageRoute () method has five overloads that can be used for having fine control for features like "Route constraints" and provide "Default values for parameters".
Now in the gamecategory.aspx page you can get the name of category passed and load that category's information on the page. So now in you PageLoad you can take advantage of a new property Page.RouteData to get the "category" value mapped using "{name}"
protected void Page_Load (object sender, EventArgs e)
if (!IsPostBack) string _categoryName = Page.RouteData.Values["name"] as string;
LoadCategory(_categoryName);
Besides getting the parameter value from code you can also use the declarative syntax to get the value in your SqlDataSource by using the new control like
Line 1 is for handling the AJAX implementation with routing as the routing breaks the AJAX resulting in "Sys is undefined or AJAX framework failed to load" error messages. Add this first up as priority is important.
My name is Emad and I develop web and software applications that help people leverage their work and and effectiveness. I love and live in this world and always looking for opportunities to collaborate and sharing ideas. I work as a software engineer and write on various day to day programming practices at My Blog.
View the original article here
Web Statistics