54

So since C# 6.0 came out, I've been using the null-conditional operator quite a lot. Example:

Model?.Person?.Zip

However, I now have a situation where I have a solution where the customer operates on domain models in the view. While I would hunt down the developer with an axe, I find it easier to just do some null checks in the view.

However, when I go this in Razor:

@Model?.Person?.Zip

My Model? is seen as dynamic, but ? breaks the dynamic things and rest is rendered as text.

How do you solve this?

Lars Holdgaard
  • 9,496
  • 26
  • 102
  • 182

4 Answers4

76

Just a guess

@(Model?.Person?.Zip)
Dieter B
  • 1,142
  • 11
  • 20
  • Can you give more information about what is not working? Example of your code? – Dieter B Apr 14 '16 at 12:13
  • This might fix the issue for Kees: http://stackoverflow.com/questions/27968963/c-sharp-6-0-features-not-working-with-visual-studio-2015 – gimlichael Nov 29 '16 at 12:08
19

For some additional completeness (I work on the ASP.NET team at Microsoft):

As Dieter B (and some others) correctly note, @(Model?.Person?.Zip) will work.

The @(...) syntax can be thought of as an "escape syntax" that allows far more flexibility in terms of which code will be parsed as the expression.

When the current version of Razor was built, only C# 5 was around, so the new C# 6 syntaxes were not directly supported.

The ASP.NET team is looking to back-port some of the Razor v4 (used in ASP.NET 5 / MVC 6) support for C# 6 back to Razor v3 (used in ASP.NET 4.x / MVC 5).

Eilon
  • 25,582
  • 3
  • 84
  • 102
  • If I'm correct, it's not really an escape character, but rather that the "?" is not basic C#. With the @(), razor knows that everything between the brackets is C# code. It can extend over various lines, so you can do entire calculations in these blocks (yes, even on 1 page) – Dieter B Oct 16 '15 at 18:04
  • Indeed you are correct, it's not an "escape character" at all. It just simplifies how much "thinking" the Razor parser needs to do because it doesn't parse C# unless it has to. By using `@(...)` it only has to do basic quote/paren matching, and little more. – Eilon Oct 17 '15 at 18:46
6

This can also happen when you're missing one or both of the following NuGet packages from the project:

  • Microsoft.CodeDom.Providers.DotNetCompilerPlatform
  • Microsoft.Net.Compilers
sunrunner20
  • 191
  • 1
  • 10
2

Just change the target framework to .NetFramework 4.7 and install these packages using Nuget package manager:

  • Microsoft.CodeDom.Providers.DotNetCompilerPlatform
  • Microsoft.Net.Compilers

Then use it like this (note the parenthesis which allow full C# syntax as opposed to partial Razor syntax):

@(Model.Country?.Name)
Mr. TA
  • 5,230
  • 1
  • 28
  • 35
Masoud Darvishian
  • 3,754
  • 4
  • 33
  • 41