InterviewSolution
| 1. |
What is Routing in MVC? |
|
Answer» Routing enables us to define a URL PATTERN that maps to the request handler.in asp.net request handler is .aspx file while in MVC request handler is controller and actions. All the route of the application is stored in RouteTable and the Routing engine helps in finding the appropriate handler class for the request, when the request and goes to the route table if it finds the appropriate actions and controller and GIVE the response and if it doesn`t FIND the controller and actions it will give the Error 404. When we CREATE the MVC application it creates one route by default which is defined under RouteConfig.cs file under AppStart Folder Eg- public class RouteConfig { Public static void RegisterRoutes(RouteCollection Routes) { routes,MapRoutes(name:”Deafult”,” url : “{controller}/{actions}/{id}”, deafults:new {controller=”Home”,action=”Index”,id=UrlParameter.Optional}); } }As we have seen in above that in Maproute() extension method of the route collection, where the name is default, URL pattern is “{controller}/{action}/{id}" Defaults specify which controller, action method or value of id PARAMETER should be used if not present in the incoming request URL. the main content of the URL is after the domain name localhost:1234/{controller}/{action}/{id}. Where localhost:1234 is the domain name, if the URL doesn't contain anything after the domain then the default request i.e Home as a controller and the Index as a view will handle the request We can also configure a custom route using MapRoute extension method. We need to provide at least two parameters in MapRoute, route name, and a URL pattern. The Defaults parameter is optional. Eg- public class RouteConfig { Public static void RegisterRoutes(RouteCollection Routes) { routes,Map Routes( name:”Default”, url:”{controller}/{actions}/{id}”, defaults:new {controller=”Home”,action=”Index”,id=UrlParameter.Optional}); routes,Map Routes( name:”Students”, url:”Students/{id}”, defaults:new {controller=”Students”,action=”Index”l}); } }In the above example, there is a custom route where controller name is Students and since there is no such action defined in the URL so the default action is an index for all the actions belongs to the controller class. |
|