【问题标题】:File Upload ASP.NET MVC (getting error)文件上传 ASP.NET MVC(出现错误)
【发布时间】: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


【解决方案1】:

这里有两个主要问题:

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

【讨论】:

  • 我把它改成了 Html.BeginForm 并且我把它改成了 enctype 但文件变量仍然作为 null 进入我的控制器
  • 谢谢。 :) 不过,我在复制您的问题时遇到了一些困难。上面的代码对我来说应该可以工作。
【解决方案2】:

null是因为“courseListViewModel”而不是因为文件

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

我发现您没有在控制器中使用“courseListViewModel modelView”。能不能删掉重试?

【讨论】:

    【解决方案3】:

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

    此外,视图中似乎缺少模型,您可能需要添加一个 @using (yourmodels).courseListViewModel 在视图顶部。如果您只是没有粘贴所有代码,那么请忘记这一点。

    我要更改的另一件事是在检查 ContentLength 之前检查您的文件是否为空。 如果文件为空,它将像现在一样抛出异常。

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 2016-05-04
      相关资源
      最近更新 更多