0

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);
}
1
  • still got the pRoblem Object reference not set to an instance of an object. null referece exception unhandl by user Commented May 20, 2014 at 9:31

1 Answer 1

1
if(files != null && files.length > 0)

it errors out because files object is null.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.