URL Routing in ASP-NET 4 Web Forms

0
3

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 transferred and loaded 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);

Beside 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.

Source

Leave a Reply