title: MVC Parent Child Modal File Upload problem
body: <p>I have a parent child scenario for getting header detail data. here is my code attached, the problem is when i use a file upload it does not work</p>
  
  <p><code>Person</code> Model:</p>
  
  <pre><code>public class Person
  {
      [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
      public int Id { get; set; }
  
      [Display(Name = "First Name")]
      [Required]
      [StringLength(255, MinimumLength = 3)]
      public string Name { get; set; }
  
      [Display(Name = "Last Name")]
      [Required]
      [StringLength(255, MinimumLength = 3)]
      public string  Surname { get; set; }
  
      public virtual ICollection&lt;Address&gt; Addresses { get; set; }
  
      [Required(AllowEmptyStrings = false, ErrorMessage = "Error: Must Choose a Country")]
      [Range(1, int.MaxValue, ErrorMessage = "Select a Country")]
      public int CountryID { get; set; }
      public virtual Country Country { get; set; }
  
  }
  </code></pre>
  
  <p><code>Address</code> Model:</p>
  
  <pre><code>public class Address
  {
      [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
      public int Id { get; set; }
  
      [Required(AllowEmptyStrings = false, ErrorMessage = "Error: Must Choose a City")]
      [Range(1, int.MaxValue, ErrorMessage = "Select a City")]
      public int CityID { get; set; }
      public virtual City City { get; set; }
  
      [Required]
      [Display(Name = "Street Address")]
      public string Street { get; set; }
  
      [Required]
      [DataType(DataType.ImageUrl)]
      public string ImageUrl { get; set; }
  
      [NotMapped]
      [DataType(DataType.Upload)]
      public HttpPostedFileBase ImageUpload { get; set; }
  
      [Required]
      [Phone]
      public string Phone { get; set; }
  
      public int PersonID { get; set; }
      public virtual Person Person  { get; set; }
  }
  </code></pre>
  
  <p><code>PeopleController</code>:</p>
  
  <pre><code>private DataDb db = new DataDb();
  
  // GET: People
  public async Task&lt;ActionResult&gt; Index()
  {
      return View(await db.People.ToListAsync());
  }
  
  // GET: People/Details/5
  public async Task&lt;ActionResult&gt; Details(int? id)
  {
      if (id == null)
      {
          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }
      Person person = await db.People.Where(p =&gt; p.Id == id).Include(p =&gt; p.Addresses).SingleAsync();
      if (person == null)
      {
          return HttpNotFound();
      }
      return View(person);
  }
  
  
  // GET: People/Edit/5
  public async Task&lt;ActionResult&gt; Edit(int? id)
  {
      if (id == null)
      {
          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }
      var person = await db.People
                  .Include(p =&gt; p.Addresses)
                  .Where(p =&gt; p.Id == id)
                  .SingleAsync();
  
      if (person == null)
      {
          return HttpNotFound();
      }
  
      ViewBag.CountryID = new SelectList(db.Country, "CountryID", "CountryName", person.CountryID);
      return View(person);
  }
  
  // POST: People/Edit/5
  // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
  // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
  [HttpPost]
  [ValidateAntiForgeryToken]
  public async Task&lt;ActionResult&gt; Edit( Person person)
  {
      if (ModelState.IsValid)
      {
          db.Entry(person).State = EntityState.Modified;
          await db.SaveChangesAsync();
          return RedirectToAction("Index");
      }
      ViewBag.CountryID = new SelectList(db.Country, "CountryID", "CountryName", person.CountryID);
  
      return View(person);
  }
  
  // GET: People/Delete/5
  public async Task&lt;ActionResult&gt; Delete(int? id)
  {
      if (id == null)
      {
          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }
      Person person = await db.People.FindAsync(id);
      if (person == null)
      {
          return HttpNotFound();
      }
      return View(person);
  }
  
  // POST: People/Delete/5
  [HttpPost, ActionName("Delete")]
  [ValidateAntiForgeryToken]
  public async Task&lt;ActionResult&gt; DeleteConfirmed(int id)
  {
      Person person = await db.People.FindAsync(id);
      db.People.Remove(person);
      await db.SaveChangesAsync();
      return RedirectToAction("Index");
  }
  </code></pre>
  
  <p><code>Address</code> Controller:</p>
  
  <pre><code>private DataDb db = new DataDb();
  
  
  public ActionResult Index(int id)
  {
      ViewBag.PersonID = id;
      var addresses = db.Addresses.Where(a =&gt; a.PersonID == id).OrderBy(a =&gt; a.City.CityName);
  
      return PartialView("_Index", addresses.ToList());
  }
  
  [ChildActionOnly]
  public ActionResult List(int id)
  {
      ViewBag.PersonID = id;
      var addresses = db.Addresses.Where(a =&gt; a.PersonID == id);
  
      return PartialView("_List", addresses.ToList());
  }
  
  public ActionResult Create(int PersonID)
  {
      //Address address = new Address();
      //address.PersonID = PersonID;
      //FillCity(address);
  
      Address adv = new Address();
      adv.PersonID = PersonID;
      FillCityModel(adv);
  
      return PartialView("_Create", adv);
  }
  
  [HttpPost]
  [ValidateAntiForgeryToken]
  public ActionResult Create(Address address, HttpPostedFileBase file)
  {
      if (ModelState.IsValid)
      {
          int addressID = clsStatic.newAddressID();
          address.Id = addressID;
  
  
          var uploadDir = "~/images";
          var imagePath = Path.Combine(Server.MapPath(uploadDir), address.ImageUpload.FileName);
          var imageUrl = Path.Combine(uploadDir, address.ImageUpload.FileName);
          address.ImageUpload.SaveAs(imagePath);
          address.ImageUrl = imageUrl;
  
          db.Addresses.Add(address);
          db.SaveChanges();
  
  
          string url = Url.Action("Index", "Addresses", new { id = address.PersonID });
          return Json(new { success = true, url = url });
      }
      FillCity(address);
      return PartialView("_Create", address);
  }
  
  public ActionResult Edit(int? id)
  {
      if (id == null)
      {
          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }
      Address address = db.Addresses.Find(id);
      if (address == null)
      {
          return HttpNotFound();
      }
      //ViewBag.CityID = new SelectList(db.City, "CityID", "CityName", address.CityID);
      FillCity(address);
      return PartialView("_Edit", address);
  }
  
  [HttpPost]
  [ValidateAntiForgeryToken]
  public ActionResult Edit(Address address )
  {
      var uploadDir = "~/images";
      if (address.ImageUpload != null)
      {
          var imagePath = Path.Combine(Server.MapPath(uploadDir), address.ImageUpload.FileName);
          var imageUrl = Path.Combine(uploadDir, address.ImageUpload.FileName);
          address.ImageUpload.SaveAs(imagePath);
          address.ImageUrl = imageUrl;
      }
      if (ModelState.IsValid)
      {
          db.Entry(address).State = EntityState.Modified;
          db.SaveChanges();
  
          string url = Url.Action("Index", "Addresses", new { id = address.PersonID });
          return Json(new { success = true, url = url });
      }
  
      //var file = Request.Files[0];
      //if (file != null &amp;&amp; file.ContentLength &gt; 0)
      //{
      //    var fileName = address.Id + Path.GetExtension(file.FileName);
      //    var path = Path.Combine(Server.MapPath("~/Images/Addresses/"), fileName);
      //    file.SaveAs(path);
      //}
  
      FillCity(address);
  
      //ViewBag.CityID = new SelectList(db.City, "CityID", "CityName", address.CityID);
      return PartialView("_Edit", address);
  }
  
  private void FillCity(Address address)
  {
      List&lt;SelectListItem&gt; city = new List&lt;SelectListItem&gt;();
  
      foreach (City item in db.City)
      {
          if (item.CityID != address.CityID)
              city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString() });
          else
              city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString(), Selected = true });
      }
  
      ViewBag.CityID = city;
  }
  
  private void FillCityModel(Address address)
  {
      List&lt;SelectListItem&gt; city = new List&lt;SelectListItem&gt;();
  
      foreach (City item in db.City)
      {
          if (item.CityID != address.CityID)
              city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString() });
          else
              city.Add(new SelectListItem { Text = item.CityName, Value = item.CityID.ToString(), Selected = true });
      }
  
      ViewBag.CityID = city;
  }
  
  public ActionResult Delete(int? id)
  {
      if (id == null)
      {
          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }
      Address address = db.Addresses.Find(id);
      if (address == null)
      {
          return HttpNotFound();
      }
      return PartialView("_Delete", address);
  }
  
  [HttpPost, ActionName("Delete")]
  [ValidateAntiForgeryToken]
  public ActionResult DeleteConfirmed(int id)
  {
      Address address = db.Addresses.Find(id);
      db.Addresses.Remove(address);
      db.SaveChanges();
  
      string url = Url.Action("Index", "Addresses", new { id = address.PersonID });
      return Json(new { success = true, url = url });
  
  }
  </code></pre>
  
  <p>Here in <code>_Edit</code> View of Address I want to have File Upload Field</p>
  
  <pre><code>@model TestAjax.Models.Address
  &lt;div class="modal-header"&gt;
      &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;&amp;times;&lt;/button&gt;
      &lt;h4 class="modal-title" id="myModalLabel"&gt;Edit Address&lt;/h4&gt;
  &lt;/div&gt;
  
  &lt;div class="modal-body"&gt;
      @using (Html.BeginForm("Edit", "Addresses", FormMethod.Post,
          new { id = "editForm", enctype = "multipart/form-data" }))
      {
          @Html.AntiForgeryToken()
          @Html.HiddenFor(model =&gt; model.PersonID)
  
          &lt;div class="form-horizontal"&gt;
              @Html.ValidationSummary(true, "", new { @class = "text-danger" })
              @Html.HiddenFor(model =&gt; model.Id)
  
              &lt;div class="form-group"&gt;
                  @Html.LabelFor(model =&gt; model.CityID, htmlAttributes: new { @class = "control-label col-md-2" })
                  &lt;div class="col-md-10"&gt;
                      @Html.DropDownListFor(model =&gt; model.CityID, (List&lt;System.Web.Mvc.SelectListItem&gt;)ViewBag.CityID, new { @class = "form-control selectpicker" })
                      @Html.ValidationMessageFor(model =&gt; model.CityID, "", new { @class = "text-danger" })
                  &lt;/div&gt;
              &lt;/div&gt;
  
              &lt;div class="form-group"&gt;
                  @Html.LabelFor(model =&gt; model.Street, htmlAttributes: new { @class = "control-label col-md-2" })
                  &lt;div class="col-md-10"&gt;
                      @Html.EditorFor(model =&gt; model.Street, new { htmlAttributes = new { @class = "form-control" } })
                      @Html.ValidationMessageFor(model =&gt; model.Street, "", new { @class = "text-danger" })
                  &lt;/div&gt;
              &lt;/div&gt;
  
                  &lt;div class="form-group"&gt;
                      @Html.LabelFor(model =&gt; model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
                      &lt;div class="col-md-10"&gt;
                          @Html.EditorFor(model =&gt; model.Phone, new { htmlAttributes = new { @class = "form-control" } })
                          @Html.ValidationMessageFor(model =&gt; model.Phone, "", new { @class = "text-danger" })
                          &lt;/div&gt;
                  &lt;/div&gt;
  
                  &lt;div class="editor-field"&gt;
                      @Html.LabelFor(m =&gt; m.ImageUpload)
                      @Html.TextBoxFor(m =&gt; m.ImageUpload, new { type = "file" })
                  &lt;/div&gt;
  
              &lt;/div&gt;
              &lt;button class="btn" type="button" data-dismiss="modal"&gt;Cancel&lt;/button&gt;
              &lt;input class="btn btn-primary" type="submit" value="Save" /&gt;
          }
      &lt;/div&gt;
      &lt;div class="modal-footer"&gt;
      Footer
  &lt;/div&gt;
  
  
  &lt;script&gt;
      $(document).ready(function () {
          refill();
      });
  
      function refill() {
          var id = @Model.CityID;
          $('#CityID').val(id);
      }
  &lt;/script&gt;
  </code></pre>
  
  <p>But when i press the save button in address controller edit action i don't have the file selected.
  please help.</p>
  
  <p><a href="https://drive.google.com/open?id=18mdmf5E39ATxE3dfSXZFkngA6-ouO4QM" rel="nofollow noreferrer">Download Source Code</a></p>