我有以下内容,但它因 NullReferenceException
而失败:
<td>@item.FundPerformance.Where(xx => fund.Id == xx.Id).FirstOrDefault().OneMonth ?? -</td>
OneMonth
定义为
public virtual decimal? OneMonth { get; set; }
失败时它的值为空。
我认为 Null Coalesce 运算符会测试它是否为 null,如果是,则返回运算符右侧的值?
我需要更改什么才能使其正常工作?
最佳答案
如您所写,razor 语法以“OneMonth”结尾。这 ??被解释为文本。要将其解释为 Razor ,您必须将整个语句包裹在 () 中,如下所示:
<td>@(item.FundPerformance.Where(xx => fund.Id == xx.Id).FirstOrDefault().OneMonth ?? "-")</td>
这仍然会给您带来错误:左边的运算符是小数,右边的运算符是字符串。因此,您可以呈现零而不是“-”,或者使用三元运算符,将 OneMonth.Value.ToString() 作为左值,将“-”作为右值。
关于c# - 如何让 Null Coalesce 运算符在 ASP.NET MVC Razor 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8444248/