Bootstrap FreeKB - MVC - Routing
MVC - Routing

Updated:   |  MVC articles

A new MVC project will automatically create the Home Controller and View. A few different URLs will all produce the same page:

  • www.example.com
  • www.example.com/Home
  • www.example.com/Home/Index

 

This is made possible by MVC Routing. The following line in the Global.asax.cs file make is possilbe to use Routing.

RouteConfig.RegisterRoutes(RouteTable.Routes);

 

The RouteConfig.cs file under the App_Start folder contains the specific configuration settings.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace www.example.com
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

 

Notice in this example the Default route has controller = "Home" and action = "Index". When www.example.com/Home is requested, /Index is automatically assumed. Likewise, when www.example.com is requested, /Home/Index is automatically assumed.




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter ac95f7 in the box below so that we can be sure you are a human.