简体   繁体   English

ASP.net MVC上传图片NullReferenceException

[英]ASP.net MVC upload image NullReferenceException

I've implemented simple create method to put data in database, and it worked fine. 我已经实现了简单的创建方法来将数据放入数据库中,并且效果很好。 I've decided to add image upload, but I keep getting NullReferenceException (file is null) and I can't figure out why. 我决定添加图片上传,但是我一直在获取NullReferenceException(文件为null),我不知道为什么。 I hope you can help me! 我希望你能帮帮我!

Here's my code: 这是我的代码:

[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);
    }
}

and View 和视图

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

EDIT 编辑

I if I wasn't clear enough: 如果我不够清楚,我会:

I know how to insert data to database and I know how to upload file, and I want when I click submit that those 2 things happen at same time 我知道如何将数据插入数据库,也知道如何上传文件,并且我希望在我单击“提交”时,这两个事情同时发生

我有两个Html.BeginForms,这是我的错,现在我将它们合并为一个,并且效果很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM