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

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

I'm not going to pass the ControllerName and the ActionName as the ViewData. I've a method that needs the ControllerName and the ActionName and I need to pass the return value of the method as the ViewData.

How can I do that?


Don't use ViewData . Use this in your Site.Master instead:

<%= ViewContext.RouteData.Values["Controller"] %>
<%= ViewContext.RouteData.Values["Action"] %>

SO - Getting the name of the controller and action method in the view in ASP.Net MVC


尝试这个:

RouteData.Values.First().Value.ToString()

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.)

链接地址: http://www.djcxy.com/p/23356.html

上一篇: 如何在HTML中使用破折号

下一篇: 获取ControllerName和ActionName并在Master Page中填充ViewData?