ASP.net MVC上传图片NullReferenceException

时间:2013-03-20 23:09:01

标签: c# asp.net-mvc entity-framework file-upload nullreferenceexception

我已经实现了简单的create方法将数据放入数据库中,并且工作正常。我已决定添加图片上传,但我一直得到NullReferenceException(文件为空),我无法弄清楚为什么。 我希望你能帮助我!

这是我的代码:

[Authorize]
    public ActionResult Create()
    {
        ViewBag.CategoryId = new SelectList(_categoryRepository.GetAllCategories().AsEnumerable(), "CategoryId",
                                            "Name");
        return View();
    }

    //
    // POST: /Advert/Create

    [HttpPost, Authorize]
    public ActionResult Create(CompetitionDTO competitionDTO, HttpPostedFileBase file)
    {
        if (file.ContentLength > 0)
        {
            string fileName = Path.GetFileName(file.FileName);
            string fileExtension = Path.GetExtension(fileName);
            if ((fileExtension == ".jpg") || (fileExtension == ".png"))
            {
                string path = Path.Combine(Server.MapPath("~/Uploads/Images"), fileName);
                file.SaveAs(path);
                competitionDTO.ImageURL = path;
            }
        }
        if (ModelState.IsValid)
        {
            _competitionRepository.AddCompetition(competitionDTO, WebSecurity.CurrentUserId);


            return RedirectToAction("Index");
        }

        ViewBag.CompetitionId = new SelectList(_competitionRepository.GetAllCompetitions().AsEnumerable(),
                                               "CompetitionId", "Name");


        return View(competitionDTO);
    }
}

和查看

<div>
        @using (Html.BeginForm("Create", "Competition", FormMethod.Post, new
            {
                enctype = "multipart/form-data"
                , id = "parentForm"
            }))
        {
            <input type="file" name="file" id="file"/>
            <input type="submit" value="Create" />
        }
    </div>

修改

我,如果我不够清楚:

我知道如何将数据插入数据库,我知道如何上传文件,我希望当我点击提交时,这两件事同时发生

1 个答案:

答案 0 :(得分:0)

我错了我有两个Html.BeginForms,现在我将它们合并为一个并且它工作正常