2012-03-17 122 views
10

我嘗試重寫和定製@Html.ActionLink,在這種方法的重載之一的參數是:查找區域名稱和控制器名稱與ASP.NET MVC3

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, 
             string linkText, string actionName); 

而且我想要的東西,像上面並且還需要找到AREANAME和ControllerName沒有傳遞由參數,我認爲使用如下:

string controller = ViewContext.RouteData.Values["Controller"]; 
string area = ViewContext.RouteData.DataTokens["Area"]; 

但錯誤崛起爲:

An object reference is required for the non-static field, method, or property 
'System.Web.Mvc.ControllerContext.RouteData.get' 

顯然我使用靜態,所以你有什麼建議找到HtmlHelpers中的區域名稱和控制器名稱?

回答

22

使用此:

string controllerName = 
(string)htmlHelper.ViewContext.RouteData.GetRequiredString("controller"); 

string areaName = 
(string)htmlHelper.ViewContext.RouteData.DataTokens["area"]; 
+0

用於動作只需使用: var actionName = htmlHelper.ViewContext.RouteData.GetRequiredString(「action」); – Roboblob 2012-06-25 09:55:59

0

我相信「控制器」和「區域」應該是小寫。下面是如何獲得的面積值:

ASP.NET MVC - Get Current Area Name in View or Controller

如果當前沒有在一個地區,將給予一個對象引用異常,所以檢查空,然後再設定值,如果它不爲空。你的控制器也是正確的,只需小寫就可以了。希望這有助於

3
public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper, 
    string linkText, 
    string actionName 
) 
{ 
    RouteData rd = htmlHelper.ViewContext.RouteData; 
    string currentController = rd.GetRequiredString("controller"); 
    string currentAction = rd.GetRequiredString("action"); 

    // the area is an optional value and it won't be present 
    // if the current request is not inside an area => 
    // you need to check if it is null or empty before using it 
    string area = rd.Values["area"] as string; 

    ... 
} 
+1

'rd.Values [ 「區」]作爲字符串;'總是返回null。 – Saeid 2012-03-17 11:25:32