title: SelectList Null on Post
body: <p>Im trying to submit a form that posts the results of cascading dropdown lists and an image back to the controller but receive the following error when using <code>Html.DropDownList</code></p>
  
  <p><code>System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable&lt;SelectListItem&gt;' that has the key 'BreedDD'.'</code> \</p>
  
  <p>When I write out the select manually it throws a <code>NullReferenceException</code></p>
  
  <p>Based on some research it appears the ViewBag will lose its value which would explain the null reference. But I haven't found any solutions that work for me and I'm at my breaking point. </p>
  
  <h1>FileUploadController.cs</h1>
  
  <pre><code>using Microsoft.Ajax.Utilities;
  using ShipleySwine;
  using System;
  using System.Collections.Generic;
  using System.Diagnostics;
  using System.IO;
  using System.Linq;
  using System.Web;
  using System.Web.Mvc;
  
  namespace UploadingFilesUsingMVC.Controllers
  {
      public class FileUploadController : Controller
      {
          private ShipleySwineContext db = new ShipleySwineContext();
          // GET: FileUpload    
          public ActionResult Index()
          {
              var breedlist = db.Boars.ToList();
              var list = breedlist.Distinct();
              var list2 = list.DistinctBy(e =&gt; e.Breed).ToList();
              List&lt;SelectListItem&gt; breedDDsli = new List&lt;SelectListItem&gt;();
              new SelectList(list2);
              foreach(var item in list2)
              {
                  breedDDsli.Add(new SelectListItem
                  {
                      Text= item.Breed,
                      Value = item.Breed
                  });
  
                  Debug.WriteLine(item.Breed);
              }
              ViewBag.breedDD = breedDDsli;
  
              return View();
          }
          [HttpPost]
          public ActionResult UploadFiles(string incomingbreed, string NameNoSpaces, HttpPostedFileBase file)
          {
              if (ModelState.IsValid)
              {
                  try
                  {
  
  
                      if (file != null)
                      {
                          string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));
                          file.SaveAs(path);
  
                      }
                      ViewBag.FileStatus = "File uploaded successfully.";
                  }
                  catch (Exception)
                  {
  
                      ViewBag.FileStatus = "Error while file uploading.";
                  }
  
              }
              return View("Index");
          }
  
          public ActionResult getBoarsList(string boarbreed)
          {
              var breedlist = db.Boars.Where(breed =&gt; breed.Breed == boarbreed).ToList();
              var list = breedlist.Distinct();
              var list2 = list.DistinctBy(e =&gt; e.Name).ToList();
              List&lt;SelectListItem&gt; boarsDD = new List&lt;SelectListItem&gt;();
              new SelectList(list2);
              foreach (var item in list2)
              {
                  boarsDD.Add(new SelectListItem
                  {
                      Text = item.NameNoSpaces,
                      Value = item.NameNoSpaces
                  });
  
                  Debug.WriteLine(item.Breed);
              }
              ViewBag.BoarsDD = boarsDD;
              return PartialView("DisplayBoars");
          }
  
          //public ActionResult boarDetails(string boarName)
          //{
          //    var boarDetails = db.Boars.Where(name =&gt; name.Name == boarName);
          //    ViewBag.boarDetails = boarDetails;
          //    return(ViewBag.boar)
          //    //return PartialView("DisplayBoarDetails");
          //}
      }
  }
  </code></pre>
  
  <h1>Index.cshtml</h1>
  
  <pre><code>@model ShipleySwine.Models.FileUpload
  @{
                  /**/
  
  
  }
  
  @using (Html.BeginForm("UploadFiles", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
  {
      @Html.AntiForgeryToken()
  
      &lt;div class="form-horizontal"&gt;
          &lt;hr /&gt;
          @Html.ValidationSummary(true, "", new { @class = "text-danger" })
          &lt;div class="form-group"&gt;
              @Html.DropDownList("BreedDD", (IEnumerable&lt;SelectListItem&gt;)ViewBag.breedDD,"-- Select Breed --", new { @class = "form-control" })
              @*&lt;select class = "form-control" id="BreedDD" name="breed"&gt;
                  &lt;option value=""&gt;-- Select Breed --&lt;/option&gt;
                  @foreach(var item in ViewBag.BreedDD)
                  {
                      &lt;option value="@item.Text"&gt;@item.Text&lt;/option&gt;
                  }
              &lt;/select&gt;*@
              &lt;select class="form-control" id="BoarsDD" name="NameNoSpaces"&gt;
  
              &lt;/select&gt;
              &lt;div class="col-md-10"&gt;
                  @Html.EditorFor(model =&gt; model.file, new { htmlAttributes = new { @class = "form-control", @type = "file" } })
                  @Html.ValidationMessageFor(model =&gt; model.file, "", new { @class = "text-danger" })
              &lt;/div&gt;
          &lt;/div&gt;
  
          &lt;div class="form-group"&gt;
              &lt;div class="col-md-offset-2 col-md-10"&gt;
                  &lt;input type="submit" value="Upload" class="btn btn-primary" /&gt;
              &lt;/div&gt;
          &lt;/div&gt;
          &lt;div class="form-group"&gt;
              &lt;div class="col-md-offset-2 col-md-10 text-success"&gt;
                  @ViewBag.FileStatus
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  }
  
  &lt;script src="~/Scripts/jquery-3.3.1.min.js"&gt;&lt;/script&gt;
  &lt;script&gt;
      $(document).ready(function () {
          $("#BreedDD").change(function () {
              var breed = $(this).val();
  
              $.ajax({
                  type: "post",
                  url: "/FileUpload/getBoarsList?boarbreed=" + breed,
                  contentType: "html",
                  success: function (response) {
  
                      $("#BoarsDD").empty();
                      $("#BoarsDD").append(response);
                  }
              })
          })
  
          //$("#BoarsDD").change(function () {
          //    var boar = $(this).val();
  
          //    $.ajax({
          //        type: "post",
          //        url: "/FileUpload/boarDetails?boarName=" + boar,
          //        contentType: "html",
          //        success: function (response) {
          //            console.log(response);
          //            console.log(response.val);
          //            $("#boarDetails").empty();
          //            $("#boarDetails").val(response);
          //        }
          //    })
          //})
      })
  &lt;/script&gt;
  </code></pre>
  
  <h1>Model</h1>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.ComponentModel.DataAnnotations;
  using System.Linq;
  using System.Web;
  
  namespace ShipleySwine.Models
  {
      public class FileUpload
      {
          [DataType(DataType.Upload)]
          [Display(Name = "Upload File")]
          [Required(ErrorMessage = "Please choose file to upload.")]
          public string file { get; set; }
          public string breed { get; set; }
          public string NameNoSpace { get; set; }
  
      }
  }
  </code></pre>