Get ControllerName and ActionName and populate the ViewData in Master Page?
Asked Answered
S

4

32

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?

Seniority answered 31/7, 2009 at 13:5 Comment(1)
for getting action ,controller names take look at this https://mcmap.net/q/101805/-get-controller-and-action-name-from-within-controllerCammack
S
62

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

Stander answered 31/7, 2009 at 13:9 Comment(1)
Those names will reflect the casing of request url. What you do with them should not be case-sensitive. (I fell in that trap.)Cassandra
L
6

Try this:

RouteData.Values.First().Value.ToString()
Lorrettalorri answered 31/7, 2009 at 13:5 Comment(1)
If you use custom routing (e.g language/controller/action) controller may not be the first entry.Michealmicheil
A
3

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

Amylum answered 31/7, 2009 at 17:15 Comment(0)
O
1

I needed to get at these alot from views, and I hit it from a slightly different angle--I wrote a few extension methods to HtmlHelper to give the current ControllerName and ActionName. A bit easier to handle as you don't need to worry about diving into the ViewData[] bag or injecting stuff at appropriate places.

Orectic answered 7/8, 2009 at 19:59 Comment(2)
I would think such extension methods would be better suited for UrlHelper, rather than HtmlHelper. Those two values really have nothing to do with HTML.Laynelayney
Good point--I think the implementation might have even got refactored that way. Theory is roughly the same in either case--pull it out rather than push it in.Orectic

© 2022 - 2024 — McMap. All rights reserved.