Routes with ASP.NET Web Pages

Det här finns att läsa på svenska här:

http://www.aspsidan.se/default.asp?page=readarticle&artId=713

With ASP.NET MVC we can get nice URLs, like /Products/Computers to show all products in the Computer category. We can set up the routes in global.asax, and can after that get the values in the controller. In ASP.NET Web Pages we don´t have neither global.asax nor controllers, so how can we use routing with this?

When we want to have dynamic pages where we show products based on the URL, we use to have something like this:

Products.cshtml?category=cars

This opens the page Products.cshtml and selects the category ”cars”. Since there is built-in support for routing in ASP.NET Web Pages, we can instead use this URL:

/Products/Category/Cars

When we go to that URL, ASP.NET Web Pages try to open Products.cshtml if it exists. If it does exist, /Category/Cars will be sent as UrlData to the page, and if it doesn´t exist it tries to open /Products/Categorycshtml and sends /Cars as UrlData and so on.

To test this we create a new file, “Products.cshtml”, and open it in the browser with the following URL: /Products/Category/Cars. What we get is the empty Products.cshtml, which means that this actually works as it should.

To get Cars from the URL we get @UrlData[1]. When get get index 1 we get Cars, since index 0 is Category. If we want to get all UrlData values, we can just loop through the object since it implements IEuerable<string>

The final code for Products.cshtml looks like this:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        @UrlData[1]
    </body>
</html>

This is what is returned to the browser:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        Cars
    </body>
</html>

We can then use this information to get a specific cateory from a database if we want too.

No Comments