使用ASP.NET MVC3在自定义Htmlhelper中查找区域名称和控制器名称

Sae*_*eid 10 asp.net-mvc static html-helper razor asp.net-mvc-3

我尝试重写和自定义@Html.ActionLink,在此方法的一个重载中,参数是:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, 
                                       string linkText,   string actionName);
Run Code Online (Sandbox Code Playgroud)

我想要像上面这样的东西,还需要找到AreaName和ControllerName而不通过参数传递它,我想使用以下内容:

string controller = ViewContext.RouteData.Values["Controller"];
string area = ViewContext.RouteData.DataTokens["Area"];
Run Code Online (Sandbox Code Playgroud)

但错误上升为:

An object reference is required for the non-static field, method, or property
'System.Web.Mvc.ControllerContext.RouteData.get'
Run Code Online (Sandbox Code Playgroud)

显然我使用静态,那你在寻找区域名称和控制器名称的建议是什么HtmlHelpers

Sae*_*eid 23

用这个:

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

string areaName = 
(string)htmlHelper.ViewContext.RouteData.DataTokens["area"];
Run Code Online (Sandbox Code Playgroud)