Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a BaseController with a ViewBag

I need to do the following: I have some Controllers ready and running, but now I want to create a BaseController. Each of my Controllers should inherit from it like this:

public class MySecondController : BaseController

thats already running so far. Now the Problem:

I want to add a ViewBag into this base controller. This ViewBag should be accessable from every view which is called in my controllers.

How to realise this?

like image 454
gurehbgui Avatar asked Apr 16 '13 10:04

gurehbgui


1 Answers

You can override OnActionExecuting method in the overridden method you can data to ViewBag dictionary.

public abstract class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ViewBag.someThing = "someThing"; //Add whatever
        base.OnActionExecuting(filterContext);
    }
}

Updated for .net Core 2019:

using Microsoft.AspNetCore.Mvc.Filters;

public abstract class BaseController : Controller
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ViewBag.someThing = "someThing"; //Add whatever
        ViewData["someThingElse"] = "this works too";
        TempData["anotherThing"] = "as does this";
        base.OnActionExecuting(filterContext);
    }
}
like image 191
Satpal Avatar answered Oct 01 '22 22:10

Satpal