Get ControllerName and ActionName and populate the ViewData in Master Page?

前端 未结 4 1448
离开以前
离开以前 2021-01-01 09:24

I\'ve a SuperController which will be inherited from all the controllers. In the constructor I\'m trying to populate the ViewData using the ControllerN

4条回答
  •  灰色年华
    2021-01-01 10:01

    Assuming that I'm reading your post correctly, and you're not trying to access the controller/action names in the view, but INSTEAD trying to do something with them, and put the result into the viewdata:

    You can't do it in the constructor because the context hasn't been created yet. You need to override the Initialize method:

    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
    
            //here the routedata is available
            ViewData["controller_name"] = (ControllerContext.RouteData.Values["Controller"];
        }
    

    (Note that you could pass in just the ControllerContext.RouteData to your function and let it pick the values it needs.)

提交回复
热议问题