Is there a recommended way to use the new
nameof()
expression in ASP.NET MVC for controller names?
Url.Action("ActionName", "Home") <------ works
vs
Url.Action(nameof(ActionName), nameof(HomeController)) <----- doesn't work
obviously it doesn't work because of nameof(HomeController) converts to "HomeController" and what MVC needs is just "Home".
It is a bit more cryptic in its style than some other languages, but you get beyond that fairly quickly. C is what is called a compiled language. This means that once you write your C program, you must run it through a C compiler to turn your program into an executable that the computer can run (execute).
To start using C, you need two things: A text editor, like Notepad, to write C code. A compiler, like GCC, to translate the C code into a language that the computer will understand.
*&n is equivalent to n . Thus the value of n is printed out. The value of n is the address of the variable p that is a pointer to int .
I like James' suggestion of using an extension method. There is just one problem: although you're using nameof()
and have eliminated magic strings, there's still a small issue of type safety: you're still working with strings. As such, it is very easy to forget to use the extension method, or to provide an arbitrary string that isn't valid (e.g. mistyping the name of a controller).
I think we can improve James' suggestion by using a generic extension method for Controller, where the generic parameter is the target controller:
public static class ControllerExtensions { public static string Action<T>(this Controller controller, string actionName) where T : Controller { var name = typeof(T).Name; string controllerName = name.EndsWith("Controller") ? name.Substring(0, name.Length - 10) : name; return controller.Url.Action(actionName, controllerName); } }
The usage is now much cleaner:
this.Action<HomeController>(nameof(ActionName));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With