Home >Backend Development >C#.Net Tutorial >How to get the name of the controller in Asp.net MVC
1, View 中
string controller = ViewContext.RouteData.Route.GetRouteData(this.Context).Values["controller"].ToString(); string controller = ViewContext.RouteData.Values["controller"].ToString();
2, controller’s action中
string controller = RouteData.Route.GetRouteData(this.HttpContext).Values["controller"].ToString(); string controller = RouteData.Values["controller"].ToString();
3 , Filter
For example, in ActionFilterAttribute, at this time, you usually implement a inherited class and then override the relevant methods.
/// <summary> /// 验证权限,用于检查用户是否已经登录(action执行前会先执行这里) /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); string controller = filterContext.RouteData.Values["controller"].ToString(); controller = controller + "Controller"; }
If you need the name of the controller in the overridden method.
4. In the public method
/// <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; }
The above is the content of the method of obtaining the name of the controller in Asp.net MVC. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!