【问题标题】:Controller action not grabbing file from view when attempting to upload尝试上传时控制器操作未从视图中抓取文件
【发布时间】:2015-10-14 07:26:23
【问题描述】:

我正在尝试将 .csv 文件上传到 SQL 数据库,但控制器操作似乎根本没有抓取该文件。查看代码,我一定漏掉了一块:

查看:

@using (Html.BeginForm("UploadValidationTable", "Home", FormMethod.Post))
{
<table style="margin-top: 150px;">
    <tr>
        <td>
            <label for="csvFile">Filename:</label>
        </td>
        <td>
            <input type="file" name="csvFile" id="csvFile"/>
        </td>
        <td><input type="submit" value="Upload"/></td>
    </tr>
</table>
}

控制器:

[HttpPost]
    public JsonResult UploadValidationTable(HttpPostedFileBase csvFile)
    {
        var inputFileDescription = new CsvFileDescription
        {
             SeparatorChar = ',',
             FirstLineHasColumnNames = true
        };
        var cc = new CsvContext();
        var filePath = uploadFile(csvFile.InputStream);
        var model = cc.Read<OutstandingCreditCsv>(filePath, inputFileDescription);

        try
        {
            var entity = new OutstandingCreditCsv();

            foreach (var item in model)
            {
                entity.PoNumber = item.PoNumber;
                entity.CreditInvoiceDate = item.CreditInvoiceDate;
                entity.CreditInvoiceNumber = item.CreditInvoiceNumber;
                entity.CreditInvoiceAmount = item.CreditInvoiceAmount;

            }
        }
        catch(LINQtoCSVException ex)
        {

        }

        return Json(model, "text/json");
    }

csvFile 只是显示为空,不知道会发生什么,因为它在视图中命名,并且我有围绕它的 post 方法。它一直持续到var filePath = uploadFile(csvFile.InputStream);,然后由于该方法试图传递一个空值而中断。谢谢!

【问题讨论】:

    标签: c# asp.net-mvc linq entity-framework file-upload


    【解决方案1】:

    不久前我在尝试使用 MVC 将文件上传到数据库时遇到了这个问题,我使用的是脚手架视图(因此它还使用表单传回了一个对象),所以它可能有点不同。

    在您的 HTML.BeginForm() 调用中,您需要添加属性 enctype="multipart/form-data"

    @using (Html.BeginForm("UploadValidationTable", "Home", FormMethod.Post, new {enctype="multipart/form-data"}))
    

    【讨论】:

    • 好吧,当我确认语法时,它被回答了...... 3 次。走吧!
    【解决方案2】:

    我认为您需要将enctype='multipart/form-data' 添加到您的&lt;form&gt;

    using (Html.BeginForm("UploadValidationTable", "Home", FormMethod.Post, 
                                 new { enctype = "multipart/form-data" }))
    

    【讨论】:

      【解决方案3】:

      您需要更改表单声明。尝试将 enctype = "multipart/form-data" 添加到您的表单声明中。

      @using (Html.BeginForm("UploadValidationTable", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))

      【讨论】:

        【解决方案4】:

        您需要在表单声明中添加以下内容:

        @using (Html.BeginForm("UploadValidationTable", "Home", null,FormMethod.Post, new { enctype =   "multipart/form-data" }))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多