Curtis
Curtis

Reputation: 103358

How can I run a method every page load in MVC3?

With WebForms, if I wanted to run a method on every page load, then I would call this method in the Page_Load() method of the main Master Page.

Is there an alternative, perhaps better solution, when using MVC3?

Upvotes: 5

Views: 8075

Answers (3)

YavgenyP
YavgenyP

Reputation: 2123

I think the most appropriate way to do this in MVC is with filters
MSDN provides a good description of them, and there are dozens of articles and explanatins about them on the net, such as this one

EDIT This sample is even better: It provides a simple action filter, which is then registered in global.asax, and executed on every request, before the actual Action in the relevan controller executes. Such concept allows you to access the request object, and modify whatever you want before the actual controller is executing.

Upvotes: 6

middelpat
middelpat

Reputation: 2585

you could create a class base controller

 public class BaseController : Controller
{

    public BaseController()
    { 
        // your code here
    }
}

and let every new controller of yours impelement the base controller like

public class MyController: BaseController

also i have found the basecontroller very usefull to store other functions i need a lot in other controllers

Upvotes: 9

David
David

Reputation: 435

You could put the code in the constructor of the controller. Like this:

public class FooController : Controller
{
    public FooController()
    {
        doThings();
    }

Upvotes: 1

Related Questions