ASP.NET MVC Razor – How to Use Null Coalesce Operator

asp.net-mvcc++null-coalescing-operatorrazor

I have the following, but it's failing with a NullReferenceException:

<td>@item.FundPerformance.Where(xx => fund.Id == xx.Id).FirstOrDefault().OneMonth ?? -</td>

OneMonth is defined as

public virtual decimal? OneMonth { get; set; }

and its value is null at the time that it fails.

I thought the Null Coalesce operator would test if its null and if so, return the value to the right of the operator?

What do I need to change to make this work?

Best Answer

The razor syntax, as you wrote it, ends at "OneMonth". The ?? are interpreted as text. To have it interpreted as razor, you must wrap the whole statements in () like this:

<td>@(item.FundPerformance.Where(xx => fund.Id == xx.Id).FirstOrDefault().OneMonth ?? "-")</td>

This will still get you an error: the left operator is a decimal and the right operator is a string. So you can either render a zero instead of "-" or use ternary operator, with OneMonth.Value.ToString() as left value and "-" as right value.

Related Question