データベースにデータを入れる単純な create メソッドを実装しましたが、うまくいきました。画像のアップロードを追加することにしましたが、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>
編集
私が十分に明確でない場合:
データベースにデータを挿入する方法とファイルをアップロードする方法を知っています。送信をクリックすると、これら2つのことが同時に起こるようにしたいです