Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 402
Curtis Avatar asked Oct 05 '12 08:10

Curtis


2 Answers

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

like image 100
middelpat Avatar answered Oct 18 '22 08:10

middelpat


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.

like image 32
YavgenyP Avatar answered Oct 18 '22 07:10

YavgenyP