Practical implementation of Routing in ASP.NET 4 is very simple. For example, consider the URL for my website that displays Label categories might look like below.
http://chelluwelcome.blogspot.com/labels.aspx?category=Microsoft
I do not want the URL to be traditional as mentioned above. I would like to see my URL as http://chelluwelcome.blogspot.com/labels/Microsoft
Can this be done? The answer is Yes. But How?
- System.Web.Routing is the new namespace that is responsible for handling ASP.NET Routing that comes along with .NET4 Framework.
- This namespace contains classes to implement URL rewriting inside ASP.NET Web Forms. We can configure the application using new ASP.NET 4 Routing Engine to accept the dynamic URL and render the same information in the web.
- ASP.NET 4.0 URL Routing, helps URLs to be mapped to ASP.NET MVC Controller classes and ASP.NET Web Forms based pages.
Step1. Import the Routing namespace in global.asax . This name space is responsible for all Routing classes.
1.
using
System.Web.Routing;
Define Routing in Global.asax, I have created a method called “RegisterRouteToAppHandler” as shown below.
1.
void
RegisterRouteToAppHandler(RouteCollection rc)
2.
{
3.
rc.MapPageRoute (
"Category"
,
//Routname
4.
"Category/{Type}"
,
//URL with parameter
5.
"~/Category.aspx"
);
//Web Form to handle
6.
}
- The RouteCollection is new collection object that comes with Routing namespace; it provides a collection of Routes for ASP.NET Routing.
- The MapPageRoute method provides a way to define routes for webform applications. This takes parameters as RouteName, URL with parameter (URL pattern of the route) and the Physical URL of the file.
Now Call the above method in application_start. Note that the category.aspx resides on application’s route directory.
1.
void
Application_Start(
object
sender, EventArgs e)
2.
{
3.
// Code that runs on application startup
4.
RegisterRouteToAppHandler(RouteTable.Routes);
5.
}
1.
"server"
postbackurl=
"~/Category/MainCategory"
>
2.
Main Category
3.
"server"
postbackurl=
"~/Category/SEO"
>
4.
SEO
5.
"server"
postbackurl=
"~/Category/ASP.NET"
>
6.
ASP.NET
7.
"server"
postbackurl=
"~/Category/CS.NET"
>
8.
C#.NET
1.
protected
void
Page_Load(
object
sender, EventArgs e)
2.
{
3.
string
strType= Page.RouteData.Values[
"Type"
]
as
string
;
4.
Response.Write(strType);
5.
}
Routing using DataAccess
Accessing with Database ASP.NET 4 comes with new control that can be used with any ASP.NET Data Source control to bind a value from a route. Consider this example that shows how can be used to bind the select statement’s @categoryID parameter from the /category/{type} parameter in the URL route.
1.
"SqlDataSource"
runat=
"server"
2.
connectionstring=
""
3.
selectcommand="select Categoryname, CategoryID from categories where categoryID =@categoryID
4.
">Type
" routekey="
5.
Type" />
No comments:
Post a Comment