Method for getting controller name in Asp. net MVC

  • 2021-08-21 20:06:44
  • OfStack

1. In the view


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

2. In the action of the controller


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

3. In the filter

For example, in ActionFilterAttribute, at this time, 1 generally implements an inherited class by itself, and then overrides related methods.

If the name of the controller is required in the overridden method.


   /// <summary>
///  Verify permissions, which are used to check whether the user is logged in ( action This will be executed before execution) 
/// </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. In the public method


   /// <summary>
///  Object for the current page Controller Full name 
/// </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;
}

Related articles: