Serge Intern
Serge Intern

Reputation: 2989

Get MVC controller name from controller's class

Is there an efficient way to get the control name "HelloWorld" when all I know is the class HelloWorldController?

Maybe something like:

var str = HelloWorldController.NetExtensionMethodWhichRetursActionName(); // str = "HelloWorld" Edit: can't exist as (currently) extension method only exist for instances

or

var str = NetUtilClass.MethodWhichRetursActionNameFromControllerclass(typeof(HelloWorldController)); // str = "HelloWorld"

or something else...

I know I could write something like:

string GetName<T>() where T : Controller { var s = typeof(T).Name; return s.Delete(s.Length - "Controller".Length; }

but I guess this functionality is already available in the framework.

Upvotes: 4

Views: 12835

Answers (5)

Bamdad
Bamdad

Reputation: 856

Why don't you just use:

string controllerName = nameof(HomeController).Replace("Controller", "");
//controllerName = "Home"

Update
For those who are obsessed with performance, the following code is about 3 times more performant:

string controllerName = nameof(HomeController);
controllerName = controllerName.Remove(controllerName.Length - 10);//10 is length of "Controller"

Upvotes: 0

Serge Intern
Serge Intern

Reputation: 2989

DefaultHttpControllerSelector has a protected method to get the controller's name base on the default <controller name>Controllerclass naming convention.

Going as far as inheriting DefaultHttpControllerSelector in a utility class could do the trick. I don't need this anymore so I'm leaving the implementation to your imagination.

Upvotes: 3

Kat
Kat

Reputation: 239

There is no built-in function that will automatically do this for you, because putting "Controller" on the end of the name is just a common practice. It's not guaranteed that the controller will actually be named that way, so checking that the type is a Controller is not enough to ensure that the function will do what you want. For this reason, I would double think your design decision to go this route. What if someone decides to rename your controller at some point? What if whatever the controller name is based on changes, but the controller name doesn't?

If you do decide to go this route, you will have to write the function yourself. Putting it in a general utility class seems like the best bet. Another possible route is to create a class which extends Controller and implements this functionality, and then have your Controllers extend that instead of Controller directly.

Upvotes: 2

Manohar Mandal
Manohar Mandal

Reputation: 31

Please try below code.

var V=RouteData.Values.First().Value.ToString();

enter image description here

Upvotes: 1

anand
anand

Reputation: 1579

In the constructor (in C#) you can get the class name:

this.GetType().Name

In an action you can get the controller name in C# from the RouteData:

RouteData.Values["controller"]

Upvotes: 0

Related Questions