我尝试重写和自定义@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
找到区域名称和控制器名称的建议是什么?
答案 0 :(得分:23)
使用此:
string controllerName =
(string)htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
string areaName =
(string)htmlHelper.ViewContext.RouteData.DataTokens["area"];
答案 1 :(得分: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;
...
}
答案 2 :(得分:0)
我认为“控制器”和“区域”应该是小写的。以下是获取面积值的方法:
ASP.NET MVC - Get Current Area Name in View or Controller
如果当前不在某个区域中,它将提供对象引用异常,因此首先检查null,然后设置该值(如果它不为null)。您的控制器也是正确的,只需小写即可。希望这有帮助