Last month I posted about separating actions into their own classes. Recently, I got a chance to try this concept out on a small project. The results, so far, have been promising. Here is a sample action controller:
public class EmployeeIndexAction() : ActionController
{
private readonly IRepository<Employee> m_employeeRepository;
public AlbumIndex(IRepository<Employee> employeeRepository)
{
m_employeeRepository= employeeRepository;
}
public ActionResult Get()
{
var employees = m_employeeRepository.FindAll();
return View(employees);
}
}
The conventions that we are using for the action controllers are:
- Create one ActionController class for each unique URL (controller and action).
- Name the class using a combination of the controller name and action name with a suffix of “Action” or more succinctly {controller}{action}Action.
- Create a method for each Http Verb (Get, Post, Put …) that is supported for the URL.
The next code example illustrates a typical edit scenario. It also shows that the action controllers still have support for binding parameters. The URL for this example is ~/employee/edit.
public class EmployeeEditAction : ActionController
{
public ActionResult Get(int id)
{
EmployeeForm form = new EmployeeForm();
// code to load employee and map to a EmployeeForm instance
return View(form);
}
public ActionResult Post(EmployeeForm form)
{
if (!ModelState.IsValid)
{
return View(form);
}
// code to map and save employee
return RedirectToAction("Index");
}
}
I created a sample application that uses action controllers. You can download the application at http://mscarman.googlecode.com/files/SampleSite.zip.
Jeffrey Palermo also posted about this subject last month. If you haven’t seen his post, check it out. His approach is a little different. But the general idea is the same and the comments are very informative as well.