【发布时间】:2014-10-04 17:16:35
【问题描述】:
我正在尝试向我的 ASP.NET Web 应用程序添加一项功能,该功能将允许用户上传包含学生课程列表的文件。我将上传功能添加到我的视图中,并在我的控制器中创建了一个新方法。每次我选择一个文件并单击上传时,我都会收到以下错误:“发生'System.NullReferenceException'类型的异常”。我猜我的文件变量即将到来是空的?下面是我的控制器代码和我的视图代码:
查看:
<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");
}
【问题讨论】:
-
您是否尝试在控制器中设置断点?
-
检查这个 SO 问题,它将指导您如何上传文件:stackoverflow.com/questions/25125127/…
-
您的代码似乎没问题,它在我这边工作没有任何问题。我只怀疑你的
TextBoxFor代码。我注释掉了该代码,除此之外一切正常。
标签: asp.net-mvc file-upload asp.net-ajax