Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C# nameof() with ASP.NET MVC Url.Action

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".

like image 247
Mikeon Avatar asked Dec 12 '14 12:12

Mikeon


People also ask

How do I use C on my computer?

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).

How do I start programming C?

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.

WHAT IS &N in C?

*&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 .


1 Answers

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)); 
like image 115
Gigi Avatar answered Sep 27 '22 23:09

Gigi