Action Selectors

Action Selectors

Action selector is the attribute that can be applied to the action methods. It aids the routing engine in selecting the appropriate action method for a given request. The following action selector attributes are included in MVC 5

  1. ActionName
  2. NonAction
  3. ActionVerbs

ActionName

As shown below, we can use the ActionName attribute to define a different action name than the method name.

public class StudentController : Controller
{
    public StudentController()
    {
    }
       
    [ActionName("Find")]
    public ActionResult GetById(int id)
    {
        // get student record 
        return View();
    }
}

The GetById() action method has been given the ActioName("find") attribute in the preceding example. Instead of GetById, the action method is now called Find. As a result, instead of http://localhost/student/getbyid/1, it will now be invoked on http://localhost/student/find/1.

NonAction

When you want a public method in a controller but don't want it to be treated as an action method, use the NonAction attribute.
The Index() method is an action method in the following example, but the GetStudent() method is not.

public class StudentController : Controller
{
    public string Index()
    {
            return "This is Index action method of StudentController";
    }
   
    [NonAction]
    public Student GetStudent(int id)
    {
        return studentList.Where(s => s.StudentId == id).FirstOrDefault();
    }
}

Post a Comment

0 Comments