The new null-conditional operator in ASP.NET MVC Razor

C#asp.net MvcRazorC# 6.0

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Just a guess

@(Model?.Person?.Zip)

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLars HoldgaardView Question on Stackoverflow
Solution 1 - C#Dieter BView Answer on Stackoverflow
Solution 2 - C#EilonView Answer on Stackoverflow
Solution 3 - C#sunrunner20View Answer on Stackoverflow
Solution 4 - C#Masoud DarvishianView Answer on Stackoverflow