我在下面的代码中选择了一个文件。但是无论我选择什么文件,我都会得到以下例外:这段代码为什么会抛出NULL异常
无法将值NULL插入到列ImgPath中。
似乎文件没有传递任何值回控制器,我做错了什么?
create.cshtml:
<div class="editor-label">
@Html.LabelFor(model => model.ImgPath)
</div>
<div class="editor-field">
<input type="file" name="file" />
</div>
首页控制器:
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);
}
太棒了!谢谢,我也在视图中缺少这一行,这就是为什么我得到文件为空。 @using(Html.BeginForm(“Create”,“Admin”,FormMethod.Post,new {enctype =“multipart/form-data”}))。如果其他人遇到同样的问题,可能会有所帮助。 – NoviceMe