Adam Levitt
Adam Levitt

Reputation: 10476

ASP.NET Razor get Area in URL

Is there a way using the ASP.NET Razor Syntax to get the area component from a request?

http://localhost:12345/SomeController/SomeAction
http://localhost:12345/MyArea/AnotherController/AnotherAction

I'd like to use Razor to cleanly and reliably get me the "MyArea" part of the URL.

What's the best approach for this?

Upvotes: 2

Views: 2136

Answers (3)

Adam Levitt
Adam Levitt

Reputation: 10476

I actually used this:

var area = ViewContext.RouteData.DataTokens["area"];

Upvotes: 3

Becuzz
Becuzz

Reputation: 6856

This should do it for you.

@ViewContext.Controller.ValueProvider.GetValue("area").RawValue.ToString()

Upvotes: 0

sgeddes
sgeddes

Reputation: 62851

I found this on another post:

String URL to RouteValueDictionary

var request = new HttpRequest(null, "http://localhost:3333/Home/About", "testvalue=1");
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response);
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

And then to get the area:

string area = routeData.DataTokens["area"].ToString();

Alternatively, you might be able to just use:

var action = RouteData.Values["area"];

Good luck.

Upvotes: 2

Related Questions