我想向我的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");
}
你有没有试图在你的控制器中放置一个断点? – ekad 2014-10-04 17:20:24
检查这个SO问题它会指导你如何上传文件:http://stackoverflow.com/questions/25125127/asp-net-mvc-4-c-sharp-httppostedfilebase-how-do-i-store-file – 2014-10-04 17:55:12
你的代码似乎很好,在我这边没有任何问题。我只怀疑你的'TextBoxFor'代码。我注意到了代码,除此之外,一切工作正常。 – ramiramilu 2014-10-04 19:33:34