Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does asp.net mvc figure it out?

How is it that I can create a method in the controller and just put some arguments and it figures it out after I click on a form submit? Under the hood, how does it find the right method and how does it figure out that I just want those arguments?

like image 288
leora Avatar asked Jul 25 '09 03:07

leora


People also ask

How does ASP.NET MVC works?

In an ASP.NET MVC application, a URL corresponds to a controller action instead of a page on disk. In a traditional ASP.NET or ASP application, browser requests are mapped to pages. In an ASP.NET MVC application, in contrast, browser requests are mapped to controller actions.

How does MVC know which Controller to use?

This is because of conventions. The default convention is /{controller}/{action} , where the action is optional and defaults to Index . So when you request /Scott , MVC's routing will go and look for a controller named ScottController , all because of conventions.

Is it hard to learn ASP.NET MVC?

It's really difficult to try and learn an entirely new language/framework under pressure. If you're required to deliver working software for your day job, trying to learn ASP.NET Core at the same time might be heaping too much pressure on yourself.

Is ASP.NET MVC still relevant?

After a strong legacy of over two decades now, the net development services still remain relevant. As per a report by w3techs, ASP.NET is still used by 7.9% of all the websites whose server-side programming languages are known.


1 Answers

In a nutshell:

  1. The routing engine handles the HttpRequest, and checks the requested URL. When it finds the first route match, it creates a new instance of MvcRouteHandler and passes it the broken-up tokens of the URL in a RouteValueDictionary.

  2. The route's MvcRouteHandler takes the request, and tries to instantiate a controller class instance. By convention, it looks for a class called "XXXXXXController", where the X's are replaced by the {controller} parameter in the route.

  3. Once it finds the controller, it invokes the appropriate method on it, given by the {action} parameter of the route. Any named arguments, such as {id}, that exist in the route, are passed as parameters to the method.

Basically, everything that ASP.Net MVC "knows" comes from the route information. It can't divine the parameters from thin air - they have to come from the route parsing. If the information isn't present in the requested URL, it can't be passed into the method.

It should also be noted that you can override the behaviour of the framework by making your routes use alternate handlers instead of MvcRouteHandler. The framework is quite extensible, so you can plug in custom functionality at many points.

like image 188
womp Avatar answered Sep 22 '22 20:09

womp