zey
zey

Reputation: 6105

check model value empty or null in javascript

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 ?

Upvotes: 1

Views: 9376

Answers (2)

Nitin S
Nitin S

Reputation: 7591

You should add it in braces with a @ symbol

e.g.

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

Upvotes: 3

Andrei
Andrei

Reputation: 56688

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.

Upvotes: 4

Related Questions