SoFunction
Updated on 2025-03-04

Methods to get the name of the controller in MVC

1. In view

string controller = ().Values["controller"].ToString();
string controller = ["controller"].ToString();

2. In the controller's action

string controller = ().Values["controller"].ToString(); 
string controller = ["controller"].ToString(); 

3. In the filter

For example, in ActionFilterAttribute, you usually implement an inheritance class yourself and then rewrite the relevant methods.

In the overridden method, if the controller name is required.

 /// <summary>
/// Verify permissions to check whether the user is logged in (there will be executed here before the action is executed)/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
(filterContext);
 string controller = ["controller"].ToString(); 
controller = controller + "Controller";
}

4. In public methods

 /// <summary>
/// Get the full name of the Controller of the current page/// </summary>
/// <returns></returns>
public string GetCurrentController()
{
string controller = ["controller"].ToString();
if (!(controller))
{
controller = controller + "Controller";
}
else
{
controller = "";
}
return controller;
}

The above is the method of obtaining the name of the controller in MVC introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!