我需要做以下事情:
我有一些控制器准备好并正在运行,但现在我想创建一个BaseController
。
我的Controllers
中的每一个都应该像这样继承它:
public class MySecondController : BaseController
到目前为止已经运行的那些。 现在问题:
我想在此基本控制器中添加ViewBag
。这个ViewBag
应该可以在我的控制器中调用的每个视图中访问。
如何实现这一目标?
答案 0 :(得分:30)
您可以在重写方法中覆盖OnActionExecuting方法,您可以将数据转换为ViewBag
字典。
public abstract class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
ViewBag.someThing = "someThing"; //Add whatever
base.OnActionExecuting(filterContext);
}
}
已针对.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);
}
}
答案 1 :(得分:0)
您还可以在新建基本控制器时填写ViewBag
Public MustInherit Class BaseController : Inherits Controller
Public Sub New()
ViewBag.ErrorMessage= "someThing"; //Add whatever
End Sub
End Class
然后将为所有继承的类调用该构造函数:
Public Class OrderController : Inherits BaseController
Function Index() As ActionResult
Return View()
End Function
End Class
可以从你的剃须刀视图中访问:
@ViewBag.ErrorMessage