繁体   English   中英

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

[英]Find Area name and Controller Name in custom Htmlhelper with ASP.NET MVC3

我尝试重写和自定义@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;

    ...
}

我认为“控制器”和“区域”应该是小写的。 以下是获取区域值的方法:

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

如果当前不在某个区域中,它将提供对象引用异常,因此首先检查null,然后设置该值(如果它不为null)。 您的控制器也是正确的,只需小写即可。 希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM