3

What might be the equivalent to a MasterPage code-behind page load in MVC? I want to check if a user is logged in my local app or facebook or twitter before every view is returned.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
billy jean
  • 1,399
  • 4
  • 25
  • 45

4 Answers4

5

Couple of options.

Create a base controller and use it's initialize method. Have your other controllers inherit it. This is probably closest to how a code behind in a MasterPage used to work.

public abstract class BaseController : Controller
{
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
       //Do Stuff
    }
}

That's the method I use for code that I want run before any Views, and for code that sets things up in the Layout view (ie: the layout stuff that's used on every page).

Alternately Global.asax is still supported, you could use Application_BeginRequest or Application_PostAcquireRequestState.

Tridus
  • 5,021
  • 1
  • 19
  • 19
  • 1
    Application_BeginRequest, I don't think this lets you check the logged in state i.e. (Request.IsAuthenticated) for some reason. So this does not work. – philbird Apr 02 '12 at 06:44
3

Use ActionFilters instead. In the framework there already is a Authorization filter. Inherit it and bend it to your will.

Read more about action filters here

Kenny Eliasson
  • 2,047
  • 15
  • 23
0

Are you using a master page?

If so, just add a call to your code in there (keep it to just a method call and implement the logic in another class).

Alternatively, derive a new View class from System.Web.UI.View, override the OnPreRender or OnLoad event and use that as the base class for your own views.

Steve Morgan
  • 12,978
  • 2
  • 40
  • 49
0

Use a partial view and include it in your master page / layout.

You can combine this with a partial action too, see here - asp.net MVC partial view controller action

The default mvc3 vstudio template contains a _logonpartial file in the views/shared directory that may be a good starting point for you

Community
  • 1
  • 1
Baldy
  • 3,621
  • 4
  • 38
  • 60