【问题标题】:Find Area name and Controller Name in custom Htmlhelper with ASP.NET MVC3使用 ASP.NET MVC3 在自定义 Htmlhelper 中查找区域名称和控制器名称
【发布时间】:2012-04-02 16:20:09
【问题描述】:

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

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 razor static html-helper


    【解决方案1】:

    使用这个:

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

    【讨论】:

    • 对于操作,只需使用: var actionName = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
    【解决方案2】:
    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;
    
        ...
    }
    

    【讨论】:

    • ` rd.Values["area"] as string;` 总是返回 null。
    【解决方案3】:

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

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

    如果当前不在一个区域中,它会给出一个对象引用异常,所以首先检查是否为空,如果它不为空,则设置该值。您的控制器也是正确的,只需小写即可。希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 2010-12-31
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      • 2012-08-03
      相关资源
      最近更新 更多