Friday 28 July 2017

Action Selectors

Always remember all public Methods are Actions in mvc

Action selector is the attribute that can be applied to the action methods. It helps routing engine to select the correct action method to handle a particular request. MVC 5 includes the following action selector attributes:
  1. ActionName
  2. NonAction
  3. ActionVerbs

ActionName:

ActionName attribute allows us to specify a different action name than the method name. Consider the following example.
Example: ActionName

public class StudentController : Controller
{

    public StudentController()
    {

    }
       
    [ActionName("find")]
    public ActionResult GetById(int id)
    {
        // get student from the database 
        return View();
    }
}

In the above example, we have applied ActioName("find") attribute to GetById action method. So now, action name is "find" instead of "GetById". This action method will be invoked on http://localhost/student/find/1 request instead of http://localhost/student/getbyid/1 request.

NonAction:

NonAction selector attribute indicates that a public method of a Controller is not an action method. Use NonAction attribute when you want public method in a controller but do not want to treat it as an action method.
For example, the GetStudent() public method cannot be invoked in the same way as action method in the following example.
Example: NonAction

public class StudentController : Controller
{
    public StudentController()
    {

    }
   
    [NonAction]
    public Student GetStudnet(int id)
    {
        return studentList.Where(s => s.StudentId == id).FirstOrDefault();
    }
}


Points to Remember :

  1. MVC framework routing engine uses Action Selectors attributes to determine which action method to invoke.
  2. Three action selectors attributes are available in MVC 5 
       - ActionName
       - NonAction
       - ActionVerbs
  3. ActionName attribute is used to specify different name of action than method name.
  4. NonAction attribute marks the public method of controller class as non-action method. It cannot be invoked.

No comments:

Post a Comment