ASP.NET - MVC - Action Selector
Action Selectors
Action Selector là các Attribute gắn với các phương thức Action. Action Selector trợ giúp cho các Route Engine lựa chọn chính xác các phương thức Action khi đáp ứng yêu của của các Http Request. Asp.Net MVC 5 bao gồm các Action Selectors sau :
- ActionName
- NonAction
- ActionVerb
2.1 ActionName
Thuộc tính ActionName cho phép sử dụng tên khác nhau của phương thức. Khi lập trình, chúng ta không muốn đưa ra tên phương thức thực thi thực sự của Controller ra phía Client.
Ví dụ :
public class StudentController : Controller
{
public StudentController()
{
}
[ActionName("find")]
public ActionResult GetById(int id)
{
// get student from the database
return View();
}
}
Hình số 2 : Ví dụ Attribute ActionName
Trong ví dụ trên, Chúng ta sử dụng Attribute ActioName("find") cho phương thức GetById.Có nghĩa, Tên phương thức "find" sẽ thay thế "GetById". Phương thức này khi gọi từ Http Request sẽ có địa chỉ URL như sau http://localhost/student/find/1 thay vì địa chỉ URL http://localhost/student/getbyid/1.
2.2 NonAction
Mục tiêu của Attribute này nhằm chỉ rõ phương thức trong controller không đóng vai trò là phương thức Action. Sử dụng Attribute NonAction khi lập trình viên muốn phương thức public trong Controller không thực hiện vai trò của một action.
Ví dụ trong Controller Student, sử dụng phương thức Student GetStudent(int id) với mục tiêu hỗ trợ các phương thức Action khác, nó không có vai trò của một phương thức Action, khi đó ta viết như sau :
public class StudentController : Controller
{
public StudentController()
{
}
[NonAction]
public Student GetStudent(int id)
{
return studentList.Where(s => s.StudentId == id).FirstOrDefault();
}
}
Points to Remember :
- MVC framework routing engine uses Action Selectors attributes to determine which action method to invoke.
- Three action selectors attributes are available in MVC 5
- ActionName
- NonAction
- ActionVerbs - ActionName attribute is used to specify different name of action than method name.
- NonAction attribute marks the public method of controller class as non-action method. It cannot be invoked.