I want to make my file upload code optional. This code is returning null reference exception handled by user.
How can I make it optional if user does not choose the file the null value should be submitted to the database?
here is the controller:
[HttpPost]
public ActionResult Create(AdulLiteracyTeachers adulliteracyteachers, HttpPostedFileBase[] files)
{
if (files.Length != null)
foreach (HttpPostedFileBase file in files)
{
string path = System.IO.Path.Combine(Server.MapPath("~/Content/Uploads/"), System.IO.Path.GetFileName(file.FileName));
if (System.IO.File.Exists(path))
{
ViewBag.Message = "File(s) Already Exist";
this.ModelState.AddModelError("", "Image with this Name Already Exist");
ViewBag.Error = TempData["Image with this Name Already Exist"];
}
else
{
file.SaveAs(path);
adulliteracyteachers.Image = file.FileName;
}
if (ModelState.IsValid)
{
db.AdulLiteracyTeachers.Add(adulliteracyteachers);
db.SaveChanges();
return RedirectToAction("Create");
}
}
ViewBag.DistID = new SelectList(db.Districts, "DistID", "DistName", adulliteracyteachers.DistID);
return View(adulliteracyteachers);
}