6

I have a class used by controllers at [Project].Controllers and by controllers at different areas. How could I determine where the controller is at? (I guess I could look at the HttpContext.Current.Request's properties -but I am looking for a "proper" MVC way). Thank you.

That is:

[Project].Helpers // called by:
[Project].Controllers
[Project].Areas.[Area].Controllers
// how could I determine the caller from [Project].Helpers?

2 Answers 2

16

We purposefully did not expose a way to get the current area name from an MVC request since "area" is simply an attribute of a route. It's unreliable for other uses. In particular, if you want your controllers to have some attribute (think of the abstract term, not the System.Attribute class) which can be used by the helper, then those attributes must be found on the controllers themselves, not on the area.

As a practical example, if you want some logic (like an action filter) to run before any controllers in a particular area, you must associate the action filter with those controllers directly. The easiest way to do this is to attribute some MyAreaBaseController with that filter, then to have each controller that you logically want to associate with that area to subclass that type. Any other usage, such as a global filter which looks at RouteData.DataTokens["area"] to make a decision, is unsupported and potentially dangerous.

If you really, really need to get the current area name, you can use RouteData.DataTokens["area"] to find it.

1
  • 1
    It's great to hear from the .NET team on this. Does your answer apply when inside a view, though? I have a shared view that's used in different areas, and I'd like to change its appearance based on where the user is on the site. I could use a partial view, but then the main view would be nearly empty. Putting something in the ViewBag seems wrong because it's strictly presentation logic. Apr 18, 2013 at 22:05
4

You should be able to get the area string from RouteData:

// action inside a controller in an area
public ActionResult Index()
{
    var area = RouteData.DataTokens["area"];
    ....
    return View();
}

.. so you can make an extension method for helpers like this:

public static class SomeHelper // in [Project].Helpers
{
    public static string Area(this HtmlHelper helper)
    {
        return (string)helper.ViewContext.RouteData.DataTokens["area"];
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.