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