Lars Holdgaard
Lars Holdgaard

Reputation: 9966

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

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?

Upvotes: 55

Views: 10828

Answers (4)

Masoud Darvishian
Masoud Darvishian

Reputation: 3964

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)

Upvotes: 2

sunrunner20
sunrunner20

Reputation: 301

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

Upvotes: 6

Eilon
Eilon

Reputation: 25704

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

Upvotes: 21

Dieter B
Dieter B

Reputation: 1142

Just a guess

@(Model?.Person?.Zip)

Upvotes: 76

Related Questions