2013-02-01 20 views
2

有沒有使用ASP.NET Razor語法從請求中獲取區域組件的方法?ASP.NET Razor在URL中獲取區域

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

我想使用Razor乾淨利落地讓我獲得URL的「MyArea」部分。

這是最好的方法是什麼?

回答

1

其實我用這個:

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

感謝!我讀過的大部分內容都說創建一個html助手類。 Soooooo很簡單的代碼。感謝您保持簡單!正是我需要的。 – HKstrongside

2

我發現這個在另一篇文章:

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

然後拿到區:

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

或者,你也許能夠只使用:

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

祝你好運。

0

這應該爲你做。

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

這將返回一個NullReferenceException。 –

+0

@AdamLevitt您可能需要檢查GetValue(「區域」)的返回值是否爲空。我假設一個空值意味着你沒有一個區域。 – Becuzz