views:

144

answers:

1

I want to know how, from a controller action, I could identify the area in which the controller is in via the MVC framework (I mean, without making all controllers in a given area inherit from a base controller with that info).

I'm particularly interested in the case of child actions (controller actions rendered via RenderAction), the area of the calling parent controller for instance.

I'm using ASP .NET MVC 2.0 RTM

+1  A: 

You can get it from the RouteData dictionary that is a member of your ControllerContext.

In your controller method (this is tested code):

string area = this.DataContext.RouteData.DataTokens["Area"].ToString();

The route that I am using looks like this:

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "MyRoute",
        MyArea/{controller}/{action}/{id},
        new {controller = "MyController", Action="Index" }
    );
}

Note that, because my area routes are more specific than my root routes (in global.asax) I am registering my area routes first.

You should check your routes using Phil Haack's route debugger, and make sure that your Url is hitting the correct route.

Robert Harvey
It doesn't work. The only key DataTokens holds in, when the child action gets executed is "Namespaces" containing the name space i mapped the parent controller to. Is there a way i could match the name space against the area?
kripto_ash
Hmm, well I would check your routes. If you are using a new operator to get the namespace isolated, it may be wiping out the rest of the routing information, but I have to believe that if you are using areas and hitting a controller method in your area, that the area appears in your route data. I will post the route entry I am using shortly.
Robert Harvey
You were right, the area key is getting set, but only for for the routes i registered via the area registration. The others (the ones i register on the bootstraper for instance) thou they had the name space assigned for disambiguation dont get the "" empty area set.Thanks for your help.
kripto_ash