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 ?

2
  • 1
    Did you try to debug it? What value does the property hold when you inspect it in debugging session? Commented Aug 13, 2018 at 9: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 . Commented Aug 13, 2018 at 9:35

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

plus one for this answer too . As @Nitin said , it should be added in braces '@(myViewModel.myInfo.Name == null ? "isNull" : "notNull")' .
3

You should add it in braces with a @ symbol

e.g.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.