ZZZ
ZZZ

Reputation: 2812

conditional operator not working well somewhere in MVC Razor?

In a cshtml file, I have a table with rows like

<td>@lic.Dealer == null ? @String.Empty : @lic.Dealer.Name</td>

However, when running, the run time keeps throwing exception complaning NullObjectReferenceException on @lic.Dealer.Name since Dealer is null.

So I had to use

var dealerName = @lic.Dealer == null ? @String.Empty : @lic.Dealer.Name;


<td>@dealerName</td>

I just wonder why the first piece code does not work well with the conditional operator?

I am using MVC5.

Upvotes: 2

Views: 753

Answers (1)

Rowan Freeman
Rowan Freeman

Reputation: 16358

Dealer is indeed null.

You forgot to wrap your statement in parentheses.

When you write this code:

<td>@lic.Dealer == null ? @String.Empty : @lic.Dealer.Name</td>

Razor does not view this as a whole statement. Instead, it tries to call ToString() on lic.Dealer because it thinks that @lic.Dealer is trying to output Dealer.

Wrap your code in parentheses, like this:

<td>@(lic.Dealer == null ? String.Empty : lic.Dealer.Name)</td>

Upvotes: 7

Related Questions