title: MVC3 cascade dropdown and Json object
body: <p>I've implemented my cascading dropdown list with MVC3 almost exactly as explained in </p>
  
  <p><a href="https://stackoverflow.com/questions/5497524/easiest-way-to-create-a-cascade-dropdown-in-asp-net-mvc-3-with-c-sharp">Easiest way to create a cascade dropdown in ASP.NET MVC 3 with C#</a></p>
  
  <p>My view had that</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      $(function () {
          $('#CategoryID').change(function () {
              var selectedCategoryId = $(this).val();
              $.getJSON('@Url.Action("SelectCategory")', { categoryid: selectedCategoryId }, function (subcategories) {
                  var subsSelect = $('#SubCategoryID');
                  subsSelect.empty();
                  $.each(subcategories, function (index, subcat) {
                      subsSelect.append(
                          $('&lt;option/&gt;')
                              .attr('value', subcat.SubCategoryID)
                              .text(subcat.SubCategoryName)
                      );
                  });
              });
          });
      });
  &lt;/script&gt;
  </code></pre>
  
  <p>My controller had that</p>
  
  <pre><code>public ActionResult SelectCategory(int categoryid)
  {
      var subs = db.SubCategories.Where(s =&gt; s.CategoryID == categoryid).ToList();
      return Json(subs, JsonRequestBehavior.AllowGet);
  }
  </code></pre>
  
  <p>And that did not work.</p>
  
  <p>However, it worked when I modified the controller the following way:</p>
  
  <pre><code>public class JsonSubCat
  {
      public int SubCategoryID { get; set; }
      public string SubCategoryName { get; set; }
  }
  
  public ActionResult SelectCategory(int categoryid)
  {
      var subs = db.SubCategories.Where(s =&gt; s.CategoryID == categoryid).ToList();
      var testsubs = new List&lt;JsonSubCat&gt;();
  
      foreach (var sub in subs)
      {
          testsubs.Add(new JsonSubCat() { SubCategoryID = sub.SubCategoryID, SubCategoryName = sub.SubCategoryName });
      }
  
      return Json(testsubs, JsonRequestBehavior.AllowGet);
  }
  </code></pre>
  
  <p>Looks like a question of converting my entities that I obtain from data source to proper format.
  What would be the correct way to implement this?</p>