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

10

我尝试重写并自定义@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中如何查找区域名称和控制器名称?

3个回答

23

使用以下代码:

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

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

1
对于操作,请使用以下代码:var actionName = htmlHelper.ViewContext.RouteData.GetRequiredString("action"); - Roboblob

4
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["area"] as string; 总是返回 null。 - Saeid

0

我认为"controller"和"area"应该小写。以下是获取区域值的方法:

ASP.NET MVC - 获取视图或控制器中的当前区域名称

如果目前不在某个区域,则会出现对象引用异常,因此请首先检查是否为空,然后在不为空的情况下设置值。您的控制器也是正确的,只需以小写形式尝试即可。希望这有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接