How can I know which Area my MVC controller action is being called in?
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开发者_JAVA百科 of the calling parent controller for instance.
I'm using ASP .NET MVC 2.0 RTM
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.
精彩评论