Asp.net-Mvc

使用 ASP.NET MVC3 在自定義 Htmlhelper 中查找區域名稱和控制器名稱

  • March 17, 2012

我嘗試重寫和自定義@Html.ActionLink,在此方法的重載之一中,參數是:

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

用這個:

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

string areaName = 
(string)htmlHelper.ViewContext.RouteData.DataTokens["area"];
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;

   ...
}

引用自:https://stackoverflow.com/questions/9748863