MVC Basic Routing Setup (Controller View) - Tarostar/SimpleNetBlog GitHub Wiki

MvcApplication::Application_Start in Global.asax.cs is a magic method called to register areas and configurations such as the routes. These configuration files are C# files located in App_start, e.g. RouteConfig.cs

In RegisterRoutes we can declare routes using MapRoute with route name, URL and parameter defaults, e.g.: routes.MapRoute("Home", "", new { controller = "Posts", action = "Index" });

Here the "controller" points to a c# file, which normally would be in the Controllers folder, and by convention is named Controller.cs, e.g. PostsController.cs.

The controller is a class derived from Controller and using System.Web.Mvc we can declare a public method that returns an ActionResult (or class derived from ActionResult), which in MVC will typically be a Adding a view, e.g.:

public ActionResult Index() { return View(); }

It could also return content, e.g. Content("admin posts");, but that would not follow the MVC pattern.

The View() calls into the Views folder and sub-folder named after the controller, and file according to the action, e.g. Views->Posts->Index.cshtml.

These cshtml razor files can contain both HTML and C# using the @{} Getting started with Razor Syntax.

In the HTML we should not use static links as an hrefin case the routing changes. Instead use razor syntax and invoke RouteUrl or RouteLink, e.g.: <a href="@Url.RouteUrl("login")">Login</a>

Note that all controllers are put in a list, regardless of folder. So if a controller in a subfolder has the same name as another controller the router might not be able to tell them apart if the path is not specific enough. E.g.: Areas->Admin->PostsController.cs and Controllers->PostController.cs.

To fix this we can use namespaces, e.g.: var namespaces = new[] { typeof(PostsController).Namespace };, and then we add the namespace as the last parameter of the MapRoute, e.g.: routes.MapRoute("Home", "", new { controller = "Posts", action = "Index" }, namespaces);

⚠️ **GitHub.com Fallback** ⚠️