我想向我的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