Understanding Route and Routing data inside a controller

by Hozefa 15. August 2012 10:39

Default route in Global.asax is expecting the url format to be www.domain.com/Home/action/id or www.domain.com/Home/action

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

where "Default" is the Route name and URL format is the second paramter in MapRoute. The third parameter sets the defaults for the parameters.

Lets say I wish to create anoter Maproute entry which will enable the url www.domain.com/myController to hit the controller named "myController" and pick up the default action of myAction once hit.

routes.MapRoute(
    "myCustomRoute", // Route name
    "myController{action}", // URL with parameters
    new { controller = "Default", action = "myAction" } // Parameter defaults
);

so if we add the above route in entry, the url www.domain.com/myController will hit the myController and then pick up the action = "myAction" from the Parameter defaults specified in the "myCustomRoute" entry.

Lets say my requirement extends and now I wish that url www.domain.com/myController/myValue should hit myController, pick up the default action myAction and pass myValue as a paramter to myAction. Then I will have to modify the route entry so it understands that myValue is actually hooked as a parameter to the default action of "myAction". The modified route entry of "myCustomRoute" will be like:

routes.MapRoute(
    "myCustomRoute", // Route name
    "myController/{value}", // URL with parameters
    new { controller = "myController", action = "myAction", value = UrlParameter.Optional } // Parameter defaults
);

and my Action in myController will look like :

public class myController : Controller
{
    //
    // GET: /Sample/

    public ActionResult myAction(string value)
    {
        return Content("Value passed is " + value);
    }

}

So the url  www.domain.com/myController/myValue will render "Value passed is myValue"

Hope this small example helps to understand the working of Route in MVC3.

Tags: ,

.NET | MVC3

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Me

Skills set includes - ASP.NET, C#, MVC3, JQuery, Javascript, HTML, AJAX and XML also hobbist programmer and geek to try out new innovations in Microsoft world.

Facebook - facebook.com/hozefam

Twitter - twitter.com/hozefam

Mail - hozefam@gmail.com

 

Month List

Page List