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?
Available in C# 6 and later, a null-conditional operator applies a member access, ?. , or element access, ?[] , operation to its operand only if that operand evaluates to non-null; otherwise, it returns null . That is, If a evaluates to null , the result of a?. x or a?[x] is null .
Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML.
it is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise, it returns the right operand. In cases where a statement could return null, the null-coalescing operator can be used to ensure a reasonable value gets returned.
Razor is a simple programming syntax for embedding server code in web pages. Razor syntax is based on the ASP.NET framework, the part of the Microsoft.NET Framework that's specifically designed for creating web applications.
Just a guess
@(Model?.Person?.Zip)
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).
This can also happen when you're missing one or both of the following NuGet packages from the project:
Just change the target framework to .NetFramework 4.7
and install these packages using Nuget package manager:
Then use it like this (note the parenthesis which allow full C# syntax as opposed to partial Razor syntax):
@(Model.Country?.Name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With