bobek
bobek

Reputation: 8020

asp.net mvc3 create a controller method that will be always executed

I have a base controller from which every other controller inherits. I would like to create a method in there that will be executed in each view. Right now I have void method in Base controller that I just call in every action in every controller.

Is that even possible to do?

Thank you,

H

Upvotes: 2

Views: 1023

Answers (1)

Paul Tyng
Paul Tyng

Reputation: 7584

The easiest way to do this is with an ActionFilterAttribute and in MVC3 you can register the attributes globally or per controller. You do not need to use a base controller.

You can define your attribute:

public class GlobalViewDataAttribute : ActionFilterAttribute { ... }

And then add it globally in your Global.asax.cs:

GlobalFilters.Filters.Add(new GlobalViewDataAttribute());

To use it on every action in a controller use:

[GlobalViewData]
public class MyController : Controller {}

Upvotes: 3

Related Questions