Blog
Choosing the Right Action - Microsoft SQL Server 2012
Excerpt by Don Kiely | December 11, 2013
The job of the action invoker to select the appropriate action method is more complicated than may appear on the surface. There could be multiple overloaded methods with the same name in a controller, they may be decorated with different attributes that make their selection appropriate in some scenarios and not others, their action method name may be different from their class method name, and other complications. Designing an effective controller requires that you understand how the selection process works. The first thing that the action invoker does is to look for the action portion of the route definition for the request. Using the default route defined in a new MVC application shown below, it is the name at the second position.
{controller}/{action}/{id}Even if the current URL doesn't include the action portion of the route, the default route definition defines it to be the "Index" action. Once the action invoker has the name of the action, it needs to map that action name to a method of the controller. The simplest case occurs when there is a single method in the controller class with a name that matches the action name. For example, in a new MVC application the Index action of the Home controller maps to the single Index method in that controller. But what qualifies as an action method? Is every method defined in the controller a potential action method? Not at all. There are a few requirements that a method must meet for the action invoker to consider it to be an action method candidate:
- It must be a public method and not marked as static.
- It cannot be a method defined on System.Object or the Controller base class. In other words, it must be defined within your custom controller object, not inherited from another object. So ToString could not be an action method because it is defined on System.Object.
- It cannot be a special method, such as a constructor, property accessor, or event accessor.
- It cannot have the NonActionAttribute decoration. This attribute is handy if you want to include a public method in a controller but don't want to use it as an action method.
WARNING! By default, anyone anywhere could invoke any public method you create in a controller, unless you decorate the method with the NonAction attribute. This sounds scary, but most of the time the only public methods you have in a controller class will be action methods, so this is a non-issue.
This post is an excerpt from the online courseware for our Microsoft SQL Server 2012 Developer course written by expert Don Kiely.Don Kiely
This course excerpt was originally posted December 11, 2013 from the online courseware SQL 2012 Developer, Part 08 of 13: Advanced T-SQL Queries by Don Kiely