.net core 在視圖中快速獲取路由(Areas、Controller、Action)


我們在.net core中,經常碰到需要獲取當前的Areas、Controller、Action,於是小編就擴展了Html,這樣即可使用

Html.***來獲取這些信息。

具體擴展類如下:

  1. public static class HtmlHelperExtensions

  2. {

  3. #region 路由操作

  4. public static HtmlString A(this IHtmlHelper helper)

  5. {

  6. return new HtmlString(helper.ViewContext.RouteData.Values["area"].ToString());

  7. }

  8. public static HtmlString C(this IHtmlHelper helper)

  9. {

  10. return new HtmlString(helper.ViewContext.RouteData.Values["Controller"].ToString());

  11. }

  12. public static HtmlString T(this IHtmlHelper helper)

  13. {

  14. return new HtmlString(helper.ViewContext.RouteData.Values["Action"].ToString());

  15. }

  16. public static HtmlString AC(this IHtmlHelper helper)

  17. {

  18. var areaName = helper.ViewContext.RouteData.Values["area"].ToString();

  19. var controllerName = helper.ViewContext.RouteData.Values["Controller"].ToString();

  20. return new HtmlString("/" + areaName + "/" + controllerName);

  21. }

  22. #endregion

  23. }

下面我們講講怎么使用,我覺得大家應該都懂了,但還是說說吧。

在視圖中使用

@Html.A() 獲取當前Areas

@Html.C() 獲取當前的Controller

@Html.T() 獲取當前的Action

@Html.AC() 獲取 Areas+Controller

是不是很簡單呢

更多精彩文章請關注我們的微信公眾號FocusDotCore


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM