Routing in MVC

Home > Search
  by

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.



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments