title: How to keep DropDownList values between a server call in ASP.NET MVC3
body: <p>I have an <strong>ASP.NET MVC3</strong> application. I have the following <code>ViewModel</code>:</p>
  
  <pre><code>public class MyViewModel
  {
      public string Year { get; set; }
      public string Month {get; set; }
  
      public IEnumerable&lt;SelectListItem&gt; Years
      {
         get
         {
             return Enumerable.Range(2000, DateTime.Now.Year - 2000).Select(x =&gt; new SelectListItem
             {
                 Value = x.ToString(),
                 Text = x.ToString()
             });
         }
      } 
  }
  </code></pre>
  
  <p>And the following <code>View</code>:</p>
  
  <pre><code>@model MyNamespace.MyViewModel
  
  @Html.DropDownListFor(
          x =&gt; x.Year, 
      new SelectList(Model.Years, "Value", "Text"),
      "-- select year --"
  )
  
  @Html.DropDownListFor(
          x =&gt; x.Month, 
      Enumerable.Empty&lt;SelectListItem&gt;(),
      "-- select month --"
  )
  </code></pre>
  
  <p>I fill the <code>DropDownList</code> for <code>Month</code> with a <code>jQuery</code> function that is triggered <code>onchange</code> from the <code>DropDownList</code> for <code>Year</code>, which works perfectly. When the form is posted to the server and then the view is rendered back I want to keep the values in the 'Month' DropDownList as it happens correctly for <code>Year</code>. Therefore I tried (besides the jQuery script):</p>
  
  <pre><code>public class MyViewModel
   {
      public string Year { get; set; }
      public string Month {get; set; }
  
      public IEnumerable&lt;SelectListItem&gt; Months
      {
          get
          {
              if(Year != null)
              {
                 return Enumerable.Range(1, 12).Select(x =&gt; new SelectListItem
                 {
                    Value = x.ToString(),
                    Text = x.ToString()
                 });
              }
          }
      }
  </code></pre>
  
  <p>And in the <code>View</code>:</p>
  
  <pre><code> @Html.DropDownListFor(
              x =&gt; x.Month, 
         new SelectList(Model.Months, "Value", "Text"),
          "-- select month --"
      )
  </code></pre>
  
  <p>I left Years out of the code to make things shorter. This code throws a <code>NullReferenceException</code> at the first run because the <code>IEnumerable</code> is empty. how can I achieve my goal?</p>