title: ASP.NET MVC jQuery not to access null model object
body: <p>I hope this is not a duplicate post.</p>
  
  <p>I have searched internet on how to find out if a model is null in jQuery. There are plenty of examples. I have tried many of them. However, I keep getting problem for this particular issue</p>
  
  <p>Here are the pseudo codes</p>
  
  <pre><code>//class declaration
  public class class2
  {
      public int var1 { get; set; }
      public int var2 { get; set; }
  }
  
  public class class1
  {
       //other properties
  
      public class2 InnerClass { get; set; }
  
  }
  
  //controller
    class1 CLASS1 = GetClass1()
    class1= GetClass1()
    CLASS1.class2 = NULL 
  
  
  
  //VIEW
  
  @model class1
  
  //java script
  var isObjectNotnull = @(Model.InnerClass != null );
  var x;
  if (isObjectNotnull )
      x = @(Model.InnerClass.var1);
  else
      x = -1;
  </code></pre>
  
  <p>The error happens in this line </p>
  
  <pre><code>x = @(Model.InnerClass.var1);
  </code></pre>
  
  <p>I got this error </p>
  
  <p><strong>Object reference not set to an instance of an object.</strong></p>
  
  <p>I thought these two statements will solve the problem</p>
  
  <pre><code>var isObjectNotnull = @(Model.InnerClass != null );
  if (isObjectNotnull )
  </code></pre>
  
  <p>Obvious, it does not help</p>
  
  <p>Then I comment out the assignment</p>
  
  <pre><code>if (isObjectNotnull )
     alert('a');
     @*x = @(Model.InnerClass.var1);*@
  </code></pre>
  
  <p>Looks like Javascript will render everything. Since Model.InnerClass is null, Javascript cannot continue to render</p>
  
  <p>What is the best approach.</p>
  
  <p>Oh, I need that variable X as part of jSon variable in Ajax variable. Originally, Model.InnerClass.var1 is assigned to jSon variable. Then I got the error, so I added the codes to check for null object, and I still could not resolve this hurdle</p>
  
  <p>Thanks</p>