C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ASP.NET MVC RoutingIn MVC, routing is a process of mapping the browser request to the controller action and return response back. Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller. The RouteConfig.cs file is used to set routing for the application. Initially it contains the following code. // RouteConfig.csusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MvcApplicationDemo { 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 } ); } } } According to this setup file, Index action of Home controller will be treated as default. First time, when application runs it produces the following output. If we look at the address bar, it contains only localhost:52174. There is no controller and action is specified because MVC router maps the controller from the RouteConfig.cs. If we explicitly enter controller and action names in the address bar, it will redirect to the same action. The localhost:52174/Home/Index will produce the same output to the browser. Now, let's create a new controller and configure it to the route file. Right click on the Controller folder and select add then controller. It will pop up a window. select an empty controller as we did in screen shot. This controller has some source code, override this with the following code. // StudentsController.csusing System.Web.Mvc; namespace MvcApplicationDemo.Controllers { public class StudentsController : Controller { public ContentResult Index() { return Content("This is default student page"); } } } To configure this controller in route file, we have made some changes in RouteConfig.cs file. Code is given below. // RouteConfig.csusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MvcApplicationDemo { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Students", url: "{controller}/{action}/{id}", defaults: new { controller = "Students", action = "Index", id = UrlParameter.Optional } ); } } } This application produce the same output for localhost:52174 and localhost:52174/Students/Index Because route module of MVC framework maps the browser URL to the RouteConfig file of the project. Output:
This is same as above even we have entered controller and action names explicitly.
Next TopicASP.NET MVC Scaffolding
|