我們在.net core中,經常碰到需要獲取當前的Areas、Controller、Action,於是小編就擴展了Html,這樣即可使用
Html.***來獲取這些信息。
具體擴展類如下:
-
public static class HtmlHelperExtensions
-
{
-
#region 路由操作
-
public static HtmlString A(this IHtmlHelper helper)
-
{
-
return new HtmlString(helper.ViewContext.RouteData.Values["area"].ToString());
-
}
-
public static HtmlString C(this IHtmlHelper helper)
-
{
-
return new HtmlString(helper.ViewContext.RouteData.Values["Controller"].ToString());
-
}
-
public static HtmlString T(this IHtmlHelper helper)
-
{
-
return new HtmlString(helper.ViewContext.RouteData.Values["Action"].ToString());
-
}
-
public static HtmlString AC(this IHtmlHelper helper)
-
{
-
var areaName = helper.ViewContext.RouteData.Values["area"].ToString();
-
var controllerName = helper.ViewContext.RouteData.Values["Controller"].ToString();
-
return new HtmlString("/" + areaName + "/" + controllerName);
-
}
-
#endregion
-
}
下面我們講講怎么使用,我覺得大家應該都懂了,但還是說說吧。
在視圖中使用
@Html.A() 獲取當前Areas
@Html.C() 獲取當前的Controller
@Html.T() 獲取當前的Action
@Html.AC() 獲取 Areas+Controller
是不是很簡單呢
更多精彩文章請關注我們的微信公眾號FocusDotCore:

