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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With