Labels

Monday, April 27, 2009

MVC || Routing || Default Routing

MVC Routing –

 

The default ASP.NET MVC routing rules are registered within the "RegisterRoutes" method of this class:

 

 

public void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 

routes.MapRoute(

"Default", // Route name – Line 1

"{controller}/{action}/{id}", // URL w/ params – Line 2

new { controller="Home", action="Index", id="" } // Param defaults – Line 3

 

);

}

 

protected void Application_Start()

{

    RegisterRoutes(RouteTable.Routes);

}

 

 

 

 

Line 2 –

 

-          "controller" is the name of the controller class to instantiate,

-          "action" is the name of a public method to invoke on it, and

-          "id" is an optional parameter embedded within the URL that can be passed as an argument to the method

 

 

Line 3 –

 

-          A set of default values to use when the url request values in the format "controller/action/id" -  does not matches the rule defined in Line 2.

-          The Default route includes defaults for all three parameters.

 

-          If you don't supply a controller, then the controller parameter defaults to the value Home.

-          If you don't supply an action, the action parameter defaults to the value Index.

-          Finally, if you don't supply an id, the id parameter defaults to an empty string.

 

 

e.g.

 

/Dinners/Details/3

 

/Dinners

 

http://localhost

Controller = Dinners

Action = Details

Id = 3

 

Controller = Dinners

Action = Index

Id = ��

 

Controller = Home

Action = Index

Id = ��

 

 

 

This wil map to –

 

 

 

Controller Actions – Based on the Default routing

 

/Home

/Home/Index

/Home/Index/3  -- Here the Id is ignored

 

/Home/Index/3

/Home/Index  -- Error

/Home/Index/3

/Home/Index  -- Pass

[HandleError]

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            return View();

        }

    }

[HandleError]

    public class HomeController : Controller

    {

        public ActionResult Index(int id)

        {

            return View();

        }

    }

[HandleError]

    public class HomeController : Controller

    {

        public ActionResult Index(int? id)

        {

            return View();

        }

    }

 

 

Hope this helps.

 

 

 

Thanks & Regards,

Arun Manglick || Senior Tech Lead

 

No comments:

Post a Comment