Reputation: 2989
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
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
Reputation: 2989
DefaultHttpControllerSelector
has a protected method to get the controller's name base on the default <controller name>Controller
class 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
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
Reputation: 31
var V=RouteData.Values.First().Value.ToString();
Upvotes: 1
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