Bobo
Bobo

Reputation: 1016

Weird Javascript If Statement

I'm not sure whats wrong with my if statement. I'm trying to use my model inside my javascript.

if (@Model !== null)
{
    if (@Model.Level !== null)
    {
        //use @Model.Level
    }
}
else
{
    //use default
}

The Model is null, but it still steps into the first if statement (and breaks on the second one obviously). I've tried @Model, !@Model and != but it still always steps in.

What am I doing wrong? (It's also got squiggly red lines under both !== saying there is a syntax error)

Upvotes: 0

Views: 203

Answers (4)

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

This code looks a LOT like a Razor then Javascript, though you may be trying to mix the two of them together.

Your choices:

1) Convert Model to a JavaScript object using something like this:
Turn C# object into a JSON string in .NET 4

2) Use the Razor if statement and write out your final JavaScript with it.

<script>
  // Code assume this is an numeric value
  var useThisVariable;
</script>

if (@Model !== null)
{
    if (@Model.Level !== null)
    {
    <script>
      useThisVariable = @Model.Level;
    </script>

    }
}
else
{
    <script>
      useThisVariable = -1;
    </script>
}

Upvotes: 0

Bura Chuhadar
Bura Chuhadar

Reputation: 3751

Triple equations work without type castings in JavaScript. In your case you are might get an undefined object which isn't a null value.

For example:

undefined === null //Do not cast when comparing, increased performance.
false
undefined == null //Do cast when comparing, decreased performance.
true

In addition, if @Model value is null then you won't see a null value on client side. It gives you an empty value like this:

if( == null)
{
}

This will cause an error on your javascript side. Null check should be done at server side. For that reason you have to put @ value in front of your code to make it server side:

<script>
    @if (Model != null) //Server side code.
        { 
            if (Model.Level != null) //still server side code.
            {

                 <text>
                   alert("your javascript here"); //write javascript on your screen.
                 </text>  
            }
        }
</script>

Upvotes: 2

TBAR
TBAR

Reputation: 448

The reason why it steps into the if statement is because it evaluates to true, no weirdness to be found here. Your browser is not temperamental. For a list comparisons check out this http://dorey.github.io/JavaScript-Equality-Table/

Also note that there is a difference between double and triple =. Triple will type cast

Upvotes: 0

genisage
genisage

Reputation: 1169

In order to check if something is null or undefined in javascript, use if (@model) rather than if ( @model !== null) http://appendto.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/

Upvotes: 0

Related Questions