Those who are currently building ASP.NET MVC web applications are very well aware of the Routing concept. URL routing enables the developer to make URLs flexible, dynamic and readable.
URL Routing was originally devised for ASP.NET MVC and has been implemented as a core feature. A route is a URL pattern which has a mapping with a handler, that can be physical file like the ASP.NET Web form .aspx.
URL routing in ASP.NET MVC and ASP.NET Web Forms differs on how you declare the final destination of the request. In ASP.NET MVC, you use a controller-action pair whereas in ASP.NET Web Forms, you use an ASPX path. In ASP.NET 4.0, URL pattern can be defined by defining its mapping with the physical .aspx file. In this pattern, a placeholder can also be defined so that variable data or parameter can be passed to the request handler without using a query string.
For defining routes in ASP.NET you need to use the following:
- Route class: It provides properties and methods for the definition of route as well as for accessing the information of routes. This class defines the specification for the routing process in ASP.NET. Route object needs to be created to define mapping for every URL pattern that needs to map with the physical file or a class handle used to handle the request.
- Routes: This is the property of the Route class. This represent the URL pattern which is used for processing incoming requests.
- RouteTable: This class is used to store the URL routes defined for the application.
Let’s see a simple example of implementing Routing in ASP.NET
Step 1: Create an ASP.NET 4.0 Web Site (or Web Application), name it as ‘ASPNET_Routing’. In the Global.asax import the ‘System.Web.Routing’ namespace as below:
Step 2: In the Application_Start write the following code:
The above code defines the routing table where the “DepartmentwiseEmployees.aspx” physical file is mapped to the URL route pattern ‘Department{DeptName}’. Here {DeptName} is the variable passed while making the request.
Step 3: In the project add a WebForm with name ‘DepartmentwiseEmployee.aspx’. Design it as below:
Step 4: Write the following code in the Loaded event of the WebForm.
The first line in the Loaded event is as below:
string deptName = (string)Page.RouteData.Values["DeptName"];
The ‘RouteData’ property of the Page class gets the route data value (in this case DeptName) of the current request context. Here this value is always a string based upon which the filtering takes place and the result will be displayed.
Step 5: Run the website and the default page will be displayed http://localhost:1091/ASPNET_Routing. In the address bar type the following URL:
http://localhost:1091/ASPNET_Routing/Department/HRD
The result will be as shown below:
Download the source code
Tweet
3 comments:
Nice article, easy to understand.
@Fabian Fernandez /signed
Thanks.
Really helpful, but can we use regular expression in the example above as we use with URL Intelligencia.
Thanks
Post a Comment