Home > Backend Development > C#.Net Tutorial > How to get the name of the controller in Asp.net MVC

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

高洛峰
Release: 2017-04-01 14:36:19
Original
2087 people have browsed it

1, View

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

2, controller’s action

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

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";
}
Copy after login

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;
}
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template