pitchie
pitchie

Reputation: 31

Global Data in ASP MVC 4

I'm writing a site for our poker league. In the _Layout page I would like to include some database information like the next game date and how many games of the season are remaining. I presume _Layout is the best page as I would like this information on ALL pages.

How can I get this entity framework data there? I presume a controller is not the way as _Layout is only a template for other views that use their own controllers.

Any information or resources would really be appreciated.

Thanks in advance,

Paul.

Upvotes: 1

Views: 714

Answers (3)

karim
karim

Reputation: 167

you can display your database information in a partial page exemple "_NextGameDate.cshtml"

then you have to include it in _Layout.cshtml page by :

 @Html.Partial("_NextGameDate.cshtml");

Upvotes: 0

Kyle
Kyle

Reputation: 1172

You can also use Html.Action like in this sample

http://kazimanzurrashid.com/posts/viewdata-or-viewbag-avoid-dependency-pollution-in-asp-dot-net-mvc-controller

Upvotes: 0

Jan
Jan

Reputation: 16032

You should create a base controller from which all your controllers inherit. There you can overwrite the method OnActionExecuting() and load that data from the DB, the cache or whereever and pass it to the Viewbag:

public class ControllerBase {
  protected override void OnActionExecuting(ActionExecutingContext ctx) {
      Viewbag.LayoutPageData = ...;
  }
}

Or you can use a base class for all your Viewmodels and pass the data with the model to the view.

Your Layout page is a view also, so you can strongly type it with a viewmodel class.

Upvotes: 1

Related Questions