Steffen
Steffen

Reputation: 13938

How to implement logic at "masterpage" level

I'm still new to MVC, so bear with me :-)

I've got a community site I'm working on, and I'd like to show how many users are online on all my pages after the user's been logged in.

I've got a shared view which is used as layout for all pages after login (UserLayout.cshtml)

Can I somehow add the logic to show online count to my shared layout ?

If it were WebForms I'd just have some code-behind for my masterpage, but this is obviously not an option here.

The information about users online is fetched from a cache. It's not available as a property on any of my View Models.

Upvotes: 6

Views: 2059

Answers (4)

GvS
GvS

Reputation: 52518

You can create a Global Action Filter.

Normally you add an Action Filter as an attribute to a method or class ([HttpPost]). Using a global Action Filter you can add code to every Action, without the need to inherit from a specific class. It is like you added an attribute to each and every Action method.

This article explains a lot.

Upvotes: 0

jonezy
jonezy

Reputation: 1923

What I did was create a BaseController.cs that all controllers inherit from, and in the base controller you can override OnActionExecuting and any viewdata values you set here will be available to your master page.

protected override void OnActionExecuting(ActionExecutingContext filterContext) {
    base.OnActionExecuting(filterContext);
}

Upvotes: 0

Jakub Konecki
Jakub Konecki

Reputation: 46008

You can create a 'UserLayoutModel' class and have all other view models derive from it. You can also use 'RenderAction' to have a part of the UI rendered separately (make sure you mark this action with ChildActionOnly attribute).

Upvotes: 1

SLaks
SLaks

Reputation: 887245

You can write an action which renders the information (using a very small view)

You can then call Html.Action to render it from the layout page.

Upvotes: 8

Related Questions