views:

133

answers:

2

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?

+7  A: 

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.

womp
From the route or the form field collection.
GalacticCowboy
The form field collection comes along with the request, but it doesn't affect how ASP.Net MVC figures things out. The form is posted to a given URL (usually to the same controller that generated the view), and that URL is handled by the routing engine.
womp
+1  A: 

There's quite a bit of code in play for controller, action and view resolution, as well as the ModelBinders. So much that it'd probably be best for you to look into specific portions of the framework and ask a more detailed question to get much of an answer.

Luckily, the ASP.NET MVC framework has been open-sourced, so if you're curious as to how it all works, you can get the code and look through it yourself. Its excellent code to read through and you're sure to learn something.

More to the point of your question, however, you should look at the System.Web.Mvc.MvcHandler and System.Web.Mvc.ControllerActionInvoker classes, which should lead you down the right path for answering your questions.

krohrbaugh