文件上传可选值

时间:2014-05-20 07:47:04

标签: asp.net-mvc

我想让我的文件上传代码可选。此代码返回null reference exception由用户处理。

如果用户没有选择应将空值提交给数据库的文件,我如何使其成为可选项?

这是控制器:

[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 个答案:

答案 0 :(得分:1)

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

它出错,因为files对象为空。