1

This is my code

 <script>
 var _getValue = @myViewModel.myInfo.Name == null ? 'isNull' : 'notNull';
 </script>

The value @myViewModel.myInfo.Name is null in database , but this code always return notNull .
How can I properly check empty or null for that ?

zey
  • 5,939
  • 14
  • 56
  • 110
  • 1
    Did you try to debug it? What value does the property hold when you inspect it in debugging session? – Andrei Aug 13 '18 at 09:30
  • yes, when I debug , `@myViewModel.myInfo.Name` is null . But It's weird , when I check like `'@myViewModel.myInfo.Name' == '' ? 'isNull' : 'notNull'` , it return `isNull` . – zey Aug 13 '18 at 09:35

2 Answers2

4

This is what happens when Razor and javascript are mixed a lot, so don't fall into habit of doing that often!

Consider this line:

 <script>
 var _getValue = @myViewModel.myInfo.Name == null ? 'isNull' : 'notNull';
 </script>

The only server-side Razor piece here is @myViewModel.myInfo.Name, which returns null, which is rendered as an empty string. So what is going to client is:

 <script>
 var _getValue = '' == null ? 'isNull' : 'notNull';
 </script>

This is pure js now, and it is executed on the client side, and naturally gives 'notNull'. After all, empty string is not null indeed.

Now consider this:

 <script>
 var _getValue = '@myViewModel.myInfo.Name' == '' ? 'isNull' : 'notNull';
 </script>

Razor piece is still the same, @myViewModel.myInfo.Name, still null, so what goes to client is:

 <script>
 var _getValue = '' == '' ? 'isNull' : 'notNull';
 </script>

This time equality actually holds, and so what you get is 'isNull'.

To fix this quickly, just follow the generic syntax to evaluate expressions in Razor:

 <script>
 var _getValue = '@(myViewModel.myInfo.Name == null ? "isNull" : "notNull")';
 </script>

Now the whole ternary thing is going to be evaluated server-side.

Going forward you might want to check out String methods IsNullOrEmpty and IsNullOrWhitespace.

Andrei
  • 55,890
  • 9
  • 87
  • 108
  • plus one for this answer too . As @Nitin said , it should be added in braces `'@(myViewModel.myInfo.Name == null ? "isNull" : "notNull")'` . – zey Aug 13 '18 at 10:54
3

You should add it in braces with a @ symbol

e.g.

<script>
    var _getValue = '@(myViewModel.myInfo.Name == null ? "isNull" : "notNull")';
</script>
Nitin Sawant
  • 7,278
  • 9
  • 52
  • 98