I have the following code where I am selecting a file. But no matter what file I select I get the following exception:
Cannot insert the value NULL into column ImgPath.
It seems like file is not passing any value back to controller, am I doing something wrong?
create.cshtml:
<div class="editor-label">
@Html.LabelFor(model => model.ImgPath)
</div>
<div class="editor-field">
<input type="file" name="file" />
</div>
Home Controller:
public ActionResult Create(TopSong topsong, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
//verify user has selected file
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath(
"~/Content/themes/base/images/Movie Images"), fileName);
file.SaveAs(path);
}
db.TopSongs.Add(topsong);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DateId = new SelectList(db.TopDates, "DateId", "DateId",
topsong.DateId);
return View(topsong);
}
You are never setting the ImgPath property on your top song object. You have a label for it in your view, but that does not assign value. If I read your code correctly, you are needing to store the image path in the database along with some other stuff, so you should just need to add one line:
But as your code stands now, it looks like you are always going to be saving a top song, even if the user does not upload an image (your saving is outside of the if statement). By refactoring your function and reducing nesting, this should do what you want it to do