asp.net-mvcasp.net-mvc-routingnerddinner

Nerd Dinners Controllers


On this page:

http://nerddinnerbook.s3.amazonaws.com/Part4.htm

After the controller is added, I can browse to http://localhost:xxxx/dinners and it works as expected. My question is how does it know to use "Dinners"? Where is "Dinners" located? My controller is named DinnersController so how did the word Dinners become meaningful. I don't see it in my Linq to SQL or anywhere else. I'm sure I'm overlooking something obvious.

Here is the code:

    //
        // HTTP-GET: /Dinners/

        public void Index()
        {
            Response.Write("<h1>Coming Soon:

Dinners"); }

        //
        // HTTP-GET: /Dinners/Details/2

        public void Details(int id)
        {
            Response.Write("<h1>Details DinnerID:

" + id + ""); }

Where is "Dinners" coming from?

Thank you for any help.

EDIT: I read further in the article before I posted and saw about the global.asax, but I don't understand how it mapped to dinners with this:

 public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }

Solution

  • ASP.NET MVC favors Convention over Configuration. Meaning it will look for a controller with a Controller suffix and not include it as part of the URL and only include the prefix to Controller. So if you have HomeController you could visit /Home/ just as DinnersController means /Dinners/. This happens as part of the ASP.NET MVC framework itself.

    If you look at the default route in Global.asax you'll see it uses a format for the URL that looks like...

    "{controller}/{action}/{id}"
    

    This means take the name of the controller and the name of the action and point the request to that method.

    So for DinnersController Index action method it would look like /Dinners/Index.