2012-09-02 226 views
0

我在下面的代码中选择了一个文件。但是无论我选择什么文件,我都会得到以下例外:这段代码为什么会抛出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); 
} 

回答

1

您从不在顶级歌曲对象上设置ImgPath属性。您在视图中有一个标签,但不会分配值。如果我正确地读你的代码,你需要的图像路径存储在与一些其他的东西沿数据库,所以你应该只需要添加一行:

topsong.ImgPath = path; 

但是作为你的代码现在站立,看起来就像你总是要保存一首歌曲一样,即使用户没有上传图片(你的保存不在if语句中)。通过重构你的功能和减少嵌套,这应该做你想做的事

public ActionResult Create(TopSong topsong, HttpPostedFileBase file) 
{ 
    if (!ModelState.IsValid) 
    { 
     ViewBag.DateId = new SelectList(db.TopDates, "DateId", "DateId",         topsong.DateId); 
     Return this.View(topsong); 
    } 

//verify user has selected file 
    if (file == null || file.ContentLength == 0) 
    { 
     ViewBag.DateId = new SelectList(db.TopDates, "DateId", "DateId",         topsong.DateId); 
     ModelState.AddModelError("file", "You must choose a file to upload."); 
     Return this.View(topsong); 
    } 

    var fileName = Path.GetFileName(file.FileName); 
    topsong.ImgPath = Path.Combine(Server.MapPath("~/Content/themes/base/images/Movie Images"), fileName); 
    file.SaveAs(topsong.ImgPath); 
    db.TopSongs.Add(topsong); 
    db.SaveChanges(); 
    return RedirectToAction("Index"); 
} 
+0

太棒了!谢谢,我也在视图中缺少这一行,这就是为什么我得到文件为空。 @using(Html.BeginForm(“Create”,“Admin”,FormMethod.Post,new {enctype =“multipart/form-data”}))。如果其他人遇到同样的问题,可能会有所帮助。 – NoviceMe

0

我猜你需要添加一个隐藏字段ImgPath。当表单提交时,只有输入字段(不是标签)不会传递给控制器​​...

+0

你能否详细说明一下?我应该删除标签吗? – NoviceMe

+0

你可以保留标签。但你还需要添加一个@ Html.HiddenFor(model => model.ImgPath) –

+0

我试过了: @ Html.HiddenFor(model => model.ImgPath )。但我认为问题不仅在于标签。当我调试文件始终为空。 – NoviceMe

相关问题