title: Check if ViewBag value is null
body: <p>I have a View in an MVC3 project, in which on load I set an Entity into the ViewBag.
  One of the entity's properties is of type <code>Datetime?</code> 
  On <code>$(document).ready</code> I load the data from ViewBag into View fields.
  In order to load the date properly, I have to parse the date:</p>
  
  <pre><code>$('#date_datepicker').datepicker("setDate", new Date('@ViewBag.Ent.MyDate.Year', '@ViewBag.Ent.MyDate.Month', '@ViewBag.Ent.MyDate.Day'));
  </code></pre>
  
  <p>Of course, I first check if the value of <code>@ViewBag.Ent.MyDate</code> is not null or empty in the following way:</p>
  
  <pre><code>if ('@ViewBag.Ent.MyDate' != null &amp;&amp; '@ViewBag.Ent.MyDate' != '')
  </code></pre>
  
  <p>Meaning, this is my code:</p>
  
  <pre><code>if ('@ViewBag.Ent.MyDate' != null &amp;&amp; '@ViewBag.Ent.MyDate' != '') {
              $('#date_datepicker').datepicker("setDate", new Date('@ViewBag.Ent.MyDate.Year', '@ViewBag.Ent.MyDate.Month', '@ViewBag.Ent.MyDate.Day'));
          }
  </code></pre>
  
  <p>But out of some reason I get
  <br />
  <strong>cannot perform runtime binding on a null reference</strong></p>
  
  <p>Here's my controller code:</p>
  
  <pre><code>public ActionResult PropertiesPage(string id)
      {
           if (!string.IsNullOrEmpty(id))
              {
                  int myID = 0;
                  int.TryParse(id, out myID);
  
                  ent = myBL.GetByEntID(myID);
                  ViewBag.Ent = ent ;
              }
  
              return View();
  
      }
  </code></pre>
  
  <p>Why does the Javascript passes my <code>if</code> statement and then fails?</p>
  
  <p><strong>Edit:</strong>
  I tried, according to Kenneth's answer to change my Javascript to:</p>
  
  <pre><code>@{if (ViewBag.Ent.MyDate != null) {
              &lt;script type="text/javascript"&gt;
                  $('#date_datepicker').datepicker("setDate", new Date('@ViewBag.Ent.MyDate.Year', '@ViewBag.Ent.MyDate.Month', '@ViewBag.Ent.MyDate.Day'));
              &lt;/script&gt;
          }
  }
  </code></pre>
  
  <p>This one won't cause an error, but it doesn't work (script fails, due to Syntax error).
  The code generates:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
                  $('#date_datepicker').datepicker("setDate", new Date('@ViewBag.Ent.MyDate.Year', '@ViewBag.Ent.MyDate.Month', '@ViewBag.Ent.MyDate.Day'));
              &lt;/script&gt;
  </code></pre>
  
  <p>(meaning, <code>&lt;script&gt;</code> within a <code>&lt;script&gt;</code>)</p>
  
  <p>Thanks</p>