1

I have fb,twitter and youtube urls in DB, and about 30 other application level variable.

currently I am querying it in each action bcz in template I have social links in footer, if missed that will throw error.

ViewBag.Contents = db.Contents.Where(s => s.status == 1).OrderBy(s => s.group).ThenBy(s => s.sort).ToList();

I want above line to be executed for all action somewhere globaly. Googled for it, many people are suggesting to put in session but i think this should not go in session variables as its size may go long.

All my controllers are inherited from Controller as

public class HomeController : Controller{}

please help.

UPDATE I have created constructor in home controller as below

public HomeController()
    {
        if (ViewBag.Contents == null)
        {
            ViewBag.Contents = db.Contents.Where(s => s.status == 1).OrderBy(s => s.sort).ToList();
        }
    }

this reduced calling it in each action, but still I have to type the same in all controllers, Is this ok or not? and how can we write this globally for all controllers

  • Stop using `ViewBag` and create a `[ChildActionOnly]` controller method that returns a partial view of your footer based on `IEnumerable` and then you can just use `@Html.Action(...)` to add that partial view to your layout. –  Sep 03 '18 at 06:21

1 Answers1

1

If you must do it that way, just create a base Controller for your application.

public class BaseController : Controller
{
     public BaseController() 
     {
        if (ViewBag.Contents == null)
        {
            ViewBag.Contents = db.Contents.Where(s => s.status == 1).OrderBy(s => s.sort).ToList();
        }
     }
}
public class HomeController : BaseController {

}

However, I would not reccomend the use of ViewBag. It's dynamic nature means you have no compile time certainty. The best route is to use a strongly typed ViewModel for each View. If you have data that you need accross all pages you can simply use a base view model.

public class BaseViewModel
{
     public List<object> Contents { get; }
     public BaseViewModel() 
     {
        if (Contents == null)
        {
            Contents = db.Contents.Where(s => s.status == 1).OrderBy(s => s.sort).ToList();
        }
     }
}
public class ViewModel: BaseViewModel {

}

Usage:

Place this at the top of your view:

@model ViewModel

You can then access contents using Razor syntax:

@Model.Contents
Jacob
  • 628
  • 5
  • 17