Routing - my simple test

Published 6/22/2009 by Dave in asp.net
Tags: ,

ASP.NET MVC comes with a routing engine, and from my understanding this will be applied to ASP.Net (I may be wrong on that). however thats not the point of this post. Today I wanted to note down some simple information about the routing engine.

The routing by default is located in the Global.asax

routes.MapRoute(
    "Default",                                              // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = ""// Parameter defaults
);

The route name must be unique
the URL can contain params which are denoted by the curly brackets
finally the default values (for this mapping)

Now lets add a Mapping, I want to be able to goto http://Mydomain/pages/aboutus, the pages just signifies that these are the pages for this website, but the last part i want to be the page name (and thus this should be able to be altered, for example, pages/contactus, or pages/someotherpage.)

The steps (If I want to use another controller, PageController.cs)

1. I think i will create the mapping first

routes.MapRoute(
    "Pages",                                //the name
    "Pages/{pageName}",                     //the url, note 1 param
    new {Controller= "Page", action="Index"}//the defaults
);

Ok you will note the URL does not contain the Controller name ("Page" in this instance) and nether the action ("Index"). these are being set by the defaults.

2. Create the controller (PageController.cs), by right clicking on the controller folder and selecting "New Controller"

public class PageController : Controller
{
    //
    // GET: /Page/

    public ActionResult Index(string pageName)
    {
        //some logic here
        return View();
    }

}

now if you add a break point at the point of the Index method, and browse to the http://myDomain/pages/yourpage, you will see the pageName param contains "yourpage". Fantastic!

If i wanted (out of curiosity) how can i just use the Home controller (provided) and just add a method called Page, I could do something like this

routes.MapRoute(
    "Pages",
    "Pages/{pageName}",
    new {Controller= "Home", action="Page"}
);

note all i had to do is change the controller and action on the default object (nice and simple), here is the method i added to the HomeController.cs

public ActionResult Page(string pageName)
{
    ViewData["Message"] = string.Format("you are veiwing the {0} page", pageName);
    return View();
}

this too populated the pageName param, which then allow me to do some logic and maybe find the data for the requested page (wahey)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

Comments are closed