我正在尝试向ASP.NET Web应用程序添加一项功能,该功能允许用户上传包含学生课程列表的文件。我将上传功能添加到我的视图中,并在我的控制器中创建了一个新方法。每次我选择一个文件并单击上传时,我都会收到以下错误:"类型' System.NullReferenceException'发生&#34 ;.我猜我的文件变量是否为null?下面是我的控制器代码和我的视图代码:
查看:
<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 :(得分:0)
这里有两个主要问题:
enctype
,而不是encrypt
。答案 1 :(得分:0)
null是因为&#34; courseListViewModel&#34;不是因为文件,
您可以设置断点并进行检查。
我发现你没有使用&#34; courseListViewModel modelView&#34;在你的控制器中。可以删除并重试吗?
答案 2 :(得分:0)
看起来你的视图模型并不存在。如果courseListViewModel是一个实际模型,它将在控制器参数中与HttpPostedFileBase类似。您可能只需要在控制器顶部添加对模型类的引用。
此外,视图中似乎缺少模型,您可能要添加一个 @using(yourmodels).courseListViewModel位于视图的顶部。如果你只是没有粘贴所有代码,那么就算了。
我要更改的另一件事是在检查ContentLength之前检查文件是否为null。 如果文件为null,它将以现在的方式抛出异常。