Using nameof() in MVC6 razor views

C# 6 introduces the new nameof() operator, which allows you to embed the name of a class, method or property easily into your code without degrading to string-based programming... String-based programming is where you use strings, where it would be better to use code...

Razor is one of those places where there are too many strings. For example, using the new tag-helpers:

<a asp-controller="HomeController" asp-action="About">About</a>

A better, more maintainable way of doing this would be

<a asp-controller="@nameof(HomeController)" asp-action="@nameof(HomeController.About)">About</a>

You might ask why? Because, for example, renaming the About method will result in Visual Studio renaming the method in your Razor views too! And if you have a typo, the compiler will warn you. That is why!

However, out of the box MVC6 does not allow this. So I've written and published a NuGet package that allows you to use this nameof() operator in MVC6 razor views.

Simply add it to your project's dependencies in project.json:

"dependencies": {
  ...
  "U2U.NameOf": "1.0.0"
}

Add the namespace of your controllers to _ViewImports.cshtml:

@using <YourProject>.Controllers

Finally open Startup.cs and add a using statement:

using U2U;

and in the ConfigureServices method add :

services.AddMvc();
services.AddNameOf();

Now open _Layout.cshtml and change all your archors to use nameof(...):

<a asp-controller="@nameof(HomeController)" asp-action="@nameof(HomeController.Index)">

You can also use this with the old-style Html helper methods:

@Html.ActionLink("test", nameof(HomeController.Contact), nameof(HomeController))

and also in code:

Url.Action(action: nameof(HomeController.About), controller: nameof(HomeController));

I hope you like it!

Next blog post will explain how it works.

Comments are closed