Home  >  Article  >  Backend Development  >  How to get the name of the controller in Asp.net MVC

How to get the name of the controller in Asp.net MVC

高洛峰
高洛峰Original
2017-04-01 14:36:191888browse

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)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn