Understanding Controller Action Method
The action methods are added to the controller class in below way.
| namespace MvcApplication1.Controllers { public class BookController : Controller { public ActionResult Index() { return View(); } } } |
In order to be exposed to the universe as an action, a method must meet certain requirements:
- The method must be public.
- The method cannot be a static method.
- The method cannot be an extension method.
- The method cannot be a constructor, getter, or setter.
- The method cannot have open generic types.
- The method is not a method of the controller base class.
- The method cannot contain ref or out parameters.
There are no restrictions on the return type of a controller action. A controller action can return a String, a DateTime, an instance of the Random class, or void. The ASP.NET MVC framework will convert any return type that is not an action result into a string and render the string to the browser.
When you add any method that does not violate these requirements to a controller, the method is exposed as a controller action.
Preventing a Public Action Method from Being Invoked
If you need to create a public method in a controller class and you don't want to expose the method as a controller action then you can prevent the method from being invoked by using the [NonAction] attribute.
Any attempt to invoke such controller action will result into an error message
| namespace MvcApplication1.Controllers { public class BookController : Controller { [NonAction] public ActionResult Index() { return View(); } } } |
Hope this helps.
Thanks & Regards,
Arun Manglick || Senior Tech Lead
No comments:
Post a Comment