MVC中如何獲取控制器的名稱


1、視圖中

string controller =ViewContext.RouteData.Route.GetRouteData(this.Context).Values["controller"].ToString();
string controller = ViewContext.RouteData.Values["controller"].ToString();

2、控制器的action中

string controller = RouteData.Route.GetRouteData(this.HttpContext).Values["controller"].ToString(); 
string controller = RouteData.Values["controller"].ToString(); 

3、過濾器中

/// <summary>
/// 過濾器中
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   base.OnActionExecuting(filterContext);
  string controller = filterContext.RouteData.Values["controller"].ToString(); 
   controller = controller + "Controller";
}

 4、公共方法中

        /// <summary>
        /// 獲取當前頁面的Controller全名稱
        /// </summary>
        /// <returns></returns>
        public string GetCurrentController()
        {
            string controller = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
            if (!string.IsNullOrWhiteSpace(controller))
            {
                controller = controller + "Controller";
            }
            else
            {
                controller = "";
            }
            return controller;
        }

 


免責聲明!

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



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