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

孤人 提交于 2019-12-03 17:26:37

问题


I try to rewrite and customize @Html.ActionLink, in one of overloads of this method the parameters are:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, 
                                       string linkText,   string actionName);

And I want something like the above and also need to find AreaName and ControllerName without pass it by parameters, I think to use the followings:

string controller = ViewContext.RouteData.Values["Controller"];
string area = ViewContext.RouteData.DataTokens["Area"];

but the error rise as :

An object reference is required for the non-static field, method, or property
'System.Web.Mvc.ControllerContext.RouteData.get'

And obviously I use static, so what is your suggestion to find Area Name and Controller Name in HtmlHelpers ?


回答1:


Use this:

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

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



回答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;

    ...
}



回答3:


I believe "controller" and "area" should be lower case. Here is how to get the area value:

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

If not currently in an area it would give a object reference exception, so check for null first and then set the value if it is not null. Your controller is also correct, just try it in lower case. Hope this helps



来源:https://stackoverflow.com/questions/9748863/find-area-name-and-controller-name-in-custom-htmlhelper-with-asp-net-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!