2012-03-17 23 views
10
私はパラメータがあり、このメソッドのオーバーロードのいずれかで、書き換え、 @Html.ActionLinkをカスタマイズしよう

ASP.NET MVC3でカスタムのHtmlHelperに地域名やコントローラ名を探す

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

そして、私は上記のような何かをしたいです

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

が、エラー上昇など:

ともパラメータで、それを渡すことなく、AREANAMEとコントローラ名を見つける必要がある、私は以下を使用することを考えます10

明らかに私は静的なものを使用していますので、エリア名とコントローラ名は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

0

「コントローラ」と「領域」は小文字にする必要があります。ここでは面積値を取得する方法である:

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

現在の領域にそれがオブジェクト参照例外を与えるので、最初はnullをチェックし、それがnullでない場合は、値を設定していない場合。あなたのコントローラーも正しいですが、小文字で試してみてください。これは

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

関連する問題