Home>Article>Backend Development> 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’saction中
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 ainheritedclass and then override the relevant methods.
////// 验证权限,用于检查用户是否已经登录(action执行前会先执行这里) /// /// 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
////// 获取当前页面的Controller全名称 /// ///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 (m.sbmmt.com)!