Can anybody please tell me why should I use the NonAction
attribute? I mean say I have a form with several submit values: Update, Delete or Insert. Since all the submit buttons have the same form in common I'm switching the submit value inside the controller and act accordingly.
Like this:
public ActionResult asd(string submitButton){
switch(submitButton){
case "Insert":
return Insert();
// bla bla bla
}
}
[NonAction]
public ActionResult Insert(){
// some code inside here
return View();
}
Once again, why should I use NonAction instead of something like this:
public void Insert(){
// some code inside here
}
The NonAction attribute is used when we want a public method in a controller but do not want to treat it as an action method. An action method is a public method in a controller that can be invoked using a URL. So, by default, if we have any public method in a controller then it can be invoked using a URL request.
The NonAction attribute is used to prevent a method from getting invoked as an action. This attribute tells to the framework that the method is not an action, inspite of it will match with routing rules or not. WEB API GET Action: // GET: api/Musics.
There is no special call for no-action methods, as we call normal call with method name. You want to access another controller no-action method?, create object for controller and access from object invoke. TestController tt = new TestController();
Action selectors are attributes that can be applied to action methods and are used to influence which action method gets invoked in response to a request. It helps the routing engine to select the correct action method to handle a particular request.
You can omit the NonAction
attribute but then the method is still invokable as action method.
From the MSDN site (ref):
By default, the MVC framework treats all public methods of a controller class as action methods. If your controller class contains a public method and you do not want it to be an action method, you must mark that method with the NonActionAttribute attribute.
It is worth noting that the need to use [NonAction]
applies only to public methods. Protected and private methods are not treated as actions. Since your Update
/Delete
/Insert
methods are helpers for asd()
, a private method would be more appropriate for your scenario:
public ActionResult asd(string submitButton){
switch(submitButton){
case "Insert":
return Insert();
// bla bla bla
}
}
ActionResult Insert(){
// some code inside here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With