2014-10-04 63 views
0

我想向我的ASP.NET Web应用程序添加一项功能,该功能将允许用户上传包含学生课程列表的文件。我添加了上传功能到我的视图,并在我的控制器中创建了一个新的方法。每次我选择一个文件并点击上传时,出现以下错误:“发生了'System.NullReferenceException'类型的异常”。我猜我的文件变量即将作为null?下面是我的控制器代码和我的视图代码:文件上传ASP.NET MVC(出现错误)

查看:

<div id="uploadCourseList"> 
     @using (Html.BeginForm("uploadCourseList", "ManageStudentCourses", FormMethod.Post, new { enctype = "multipart/form-data" })) 
     { 
      @Html.AntiForgeryToken() 
      @Html.TextBoxFor(x => Model.userId, @Model.userId, new { @class = "addCourseTxtBoxId" }) 
      <table class="courseListTable"> 
       <tr> 
        <th colspan="4"> 
         Upload Course List 
        </th> 
       </tr> 
       <tr> 
        <td> 
         Select a file: 
        </td> 
        <td> 
         <input type="file" name="file" id="file" /> 
        </td> 
        <td> 
         <input type="submit"> 
        </td> 
       </tr> 
      </table> 
     } 
    </div> 

控制器

public PartialViewResult uploadCourseList(HttpPostedFileBase file, courseListViewModel modelView) 
    { 
     if (file.ContentLength > 0 && file != null) 
     { 
      string path = Path.Combine(Server.MapPath("~/Content/courseList"), Path.GetFileName(file.FileName)); 
      file.SaveAs(path); 
     } 
    return PartialView("~/Views/ManageStudentCourses/listCourses.cshtml"); 
    } 
+0

你有没有试图在你的控制器中放置一个断点? – ekad 2014-10-04 17:20:24

+0

检查这个SO问题它会指导你如何上传文件:http://stackoverflow.com/questions/25125127/asp-net-mvc-4-c-sharp-httppostedfilebase-how-do-i-store-file – 2014-10-04 17:55:12

+0

你的代码似乎很好,在我这边没有任何问题。我只怀疑你的'TextBoxFor'代码。我注意到了代码,除此之外,一切工作正常。 – ramiramilu 2014-10-04 19:33:34

回答

0

您这里有两个主要问题:

  1. 属性的表单标签应该是enctype,而不是encrypt
  2. 您无法使用Ajax.BeginForm发送文件,至少不会像您想象的那样轻松发送文件。快速解决方案是使用Html.BeginForm(),但如果这是不可接受的,那么您可能需要查看第三方插件,例如Plupload
+0

我将它改为Html.BeginForm,然后我将其更改为enctype,但该文件变量仍然以空值形式进入我的控制器 – Stc5097 2014-10-04 19:10:04

+0

请您可以共享新的表单代码吗? :) – Tobias 2014-10-04 19:15:45

+0

上面的代码更新:) – Stc5097 2014-10-04 19:19:43

0

空是因为“courseListViewModel”不是因为文件

,你可以设置断点,并检查它。

我发现你没有在控制器中使用“courseListViewModel modelView”。它可以被删除并重试吗?

0

它看起来好像您的视图模型不存在。如果courseListViewModel是一个实际的模型,它将在你的控制器参数中类似于HttpPostedFileBase。您可能需要在控制器的顶部添加对模型类的引用。

此外,模型似乎从视图中缺失,您可能想在视图的顶部添加一个 @using(yourmodels).courseListViewModel。如果你只是没有粘贴所有的代码,然后忘记这一点。

我会改变的另一件事是检查您的文件是否为空之前检查ContentLength。 如果该文件为空,它将以现在的方式抛出异常。