簡體   English   中英

ASP.net MVC上傳圖片NullReferenceException

[英]ASP.net MVC upload image NullReferenceException

我已經實現了簡單的創建方法來將數據放入數據庫中,並且效果很好。 我決定添加圖片上傳,但是我一直在獲取NullReferenceException(文件為null),我不知道為什么。 我希望你能幫幫我!

這是我的代碼:

[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>

編輯

如果我不夠清楚,我會:

我知道如何將數據插入數據庫,也知道如何上傳文件,並且我希望在我單擊“提交”時,這兩個事情同時發生

我有兩個Html.BeginForms,這是我的錯,現在我將它們合並為一個,並且效果很好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM