[英]MVC Why is RouteData null?
I'm trying to change the default ViewBag.Title for all my controllers, so I though about making a base class that inherit from Controller and handle the title there: 我正在尝试为我的所有控制器更改默认的ViewBag.Title,所以我想创建一个继承自Controller的基类并在那里处理标题:
public class MyController : Controller
{
public MyController()
: base()
{
var controller = default(object);
if (RouteData.Values.TryGetValue("controller", out controller))
{
ViewBag.Title = controller;
}
}
}
Then inherit that class from my controllers : 然后从我的控制器继承该类:
public class GlobalSettingsController : MyController
{
But when I run the page I get a null reference exception because RouteData is null. 但是当我运行页面时,我得到一个空引用异常,因为RouteData为null。
How comes it's null? 它是怎么回事? And what can I do? 我该怎么办?
you are executing the code inside the constructor, before any values is assigned to the controller. 在将任何值分配给控制器之前,您正在构造函数内执行代码。
A better place to do this is in OnActionExecuting like this: 更好的地方是OnActionExecuting这样:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
var controller = default(object);
if (RouteData.Values.TryGetValue("controller", out controller))
{
ViewBag.Title = controller;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.