Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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?

share|improve this question
10  
Just a guess @(Model?.Person?.Zip) – Dieter B 11 hours ago
2  
@DieterB Haha, that is so simple... AND IT WORKED. Awesome. Could you put an answer for all the future Googlers who are just as stupid as me? – Lars Holdgaard 11 hours ago
    
Done. Thnx for the confirmation ;-) – Dieter B 11 hours ago

2 Answers 2

up vote 24 down vote accepted

Just a guess

@(Model?.Person?.Zip)
share|improve this answer

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

share|improve this answer
    
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 6 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.