Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Private methods and Actions decorated with NonAction in Asp.Net MVC

in Asp.Net MVC if I decorate an action method with attribute NonAction then it wont be allowed to be called by the user visiting the site. same happens when I make it private

So whats the difference between the two and is there a special purpose for which NonAction attribute has been made?

For example whats the difference between

[NonAction]
public ActionResult SomeAction(){}

And

private ActionResult SomeAction(){}

in the context of asp.net MVC of course I know one is public and the other one is private

like image 352
Parv Sharma Avatar asked Feb 09 '13 10:02

Parv Sharma


People also ask

What is NonAction method in MVC?

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.

Can action method be private in MVC?

So, every public method inside the Controller is an action method in MVC. Action Method can not be a private or protected method. If you provide the private or protected access modifier to the action method, it will provide the error to the user, i.e., “resource can not be found” as below.

Are there any non action method in MVC?

To restrict access to public methods in a Controller, a Non-Action attribute can be used. Non-Action is another built-in attribute which indicates that a public method of a Controller is not an action method. It is used when we don't want that method to be treated as an action method.


1 Answers

That's the only difference. The attribute is used when you want a method that has a signature that would make it an action, but that you don't want to be an action.

An example for a use for that is a method that action methods call to produce the ActionResult for them:

[NonAction]
public JsonResult JsonInfo(string id, string value) {
  return Json(new { id = id, value = value });
}

public JsonResult GetBusInfo() {
  return JsonInfo("4", "Bus");
}

public JsonResult GetCarInfo() {
  return JsonInfo("8", "Car");
}

The reason to make it public instead of private would be so that actions in other controllers could also use it.

like image 80
Guffa Avatar answered Sep 19 '22 13:09

Guffa