Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "nameof" operator in Razor views

On my VS.NET 2015 development machine, the Razor views that use the nameof operator work like a charm.

When deploying to a Windows server, it fails to compile the CSHTML Razor views:

The name 'nameof' does not exist in the current context.

In German:

Der Name 'nameof' ist im aktuellen Kontext nicht vorhanden.

I've installed .NET Framework 4.6 ("ASP.NET version: 4.6.81.0") with no success.

Most likely I'm missing something plain simple.

Still, I'm really clueless. Is it a web.config setting? Or something else?

My question:

How to enable C# 6 features (like the nameof operator) in CSHTML Razor views?

like image 990
Uwe Keim Avatar asked Nov 20 '15 09:11

Uwe Keim


People also ask

What is Nameof operator in C#?

C# NameOf operator is used to get name of a variable, class or method. It returns a simple string as a result. In error prone code, it is useful to capture a method name, in which error occurred. We can use it for logging, validating parameters, checking events etc.

When was Nameof added to C#?

The nameof operator, added in C# 6.0, addresses this — it allows capturing the string names of symbols that are in the scope.

What is the Nameof?

idiom. : used to indicate the name that is used for someone or something.


2 Answers

According to this site, you need to reference the Roslyn compiler in your Web.config file to get C# 6 features to work in your razor views.

This can be achieved simply by installing the CodeDOM Providers for .NET Compiler NuGet package.

PM> Install-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform 
like image 106
Jamie Dunstan Avatar answered Sep 22 '22 00:09

Jamie Dunstan


Make sure in your file "web.config" the node system.codedom exists.

<system.codedom>     <compilers>       <compiler language="c#;cs;csharp" extension=".cs"         type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"         warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>       <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"         type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"         warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>     </compilers>  </system.codedom> 

And you'd reference the package Microsoft.CodeDom.Providers.DotNetCompilerPlatform.

like image 30
chsword Avatar answered Sep 20 '22 00:09

chsword