Home

Vici MVC Quick Walkthrough - Part 7 - BeforeAction/AfterAction methods

The framework can call methods on your controller object before and after your "main" action method automatically. This can be useful to specify an alternate view for some users, to perform authentication, or whatever crosses your mind.

You can do that by adding the [Setup] or [Teardown] attributes to methods of your controller class. The [Setup] attribute tells Vici MVC to execute the method before the action method. As you may have guessed, the [Teardown] attribute will cause the method to be called after the action method.

The best way to use this feature is by creating base classes for your controller pages. For example, if you have a set of pages that are only available for users that are already authenticated (logged in), you can create two base classes with setup methods defined:

public class PublicController : Controller
{
   [BeforeAction]
   private void SetLayout()
   {
       ChangeLayout("PublicLayout");
   }
}

public class AuthenticatedController : Controller
{
   [BeforeAction]
   private void Authenticate()
   {
       if (!(bool)Session["Authenticated"])
          Redirect("~/login");
   }
}

You can then use these classes as the base class for your controllers:

// Note: we didn't specify a view because by default the view is the same name as the class
public class AboutUs : PublicController
{
   // ...
}
 
public class MyAccount : AuthenticatedController
{
   // ...
}

>> Next: Part 8