How to create a BaseController with a ViewBag

2020-08-09 09:59发布

问题:

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?

回答1:

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);
    }
}


回答2:

You can also just fill the ViewBag when newing up the base controller

Public MustInherit Class BaseController : Inherits Controller

    Public Sub New()
        ViewBag.ErrorMessage= "someThing"; //Add whatever
    End Sub

End Class

Then that constructor will get called for all inherited classes:

Public Class OrderController : Inherits BaseController 

    Function Index() As ActionResult
        Return View()
    End Function

End Class

And accessible from the your razor view:

@ViewBag.ErrorMessage