c# - 尝试上传时 Controller 操作未从 View 中抓取文件

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

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

查看:

@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>
}

Controller :

[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 只是显示为 null,不知道会发生什么,因为它在 View 中被命名并且我有围绕它的 post 方法。它一直下降到 var filePath = uploadFile(csvFile.InputStream); 然后中断,因为该方法试图传递空值。谢谢!

最佳答案

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

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

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

关于c# - 尝试上传时 Controller 操作未从 View 中抓取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31596701/

相关文章:

asp.net-mvc - 如何使用asp.net mvc EditorTemplate

c# - LINQ-to-SQL Table<T>.Attach 有什么作用?

c# - 简化IF语句逻辑——内部逻辑重叠

c# - Entity Framework 区域设置配置

asp.net - 如何将 kendo Ui 下拉列表选定值的 ID 传递到 Controller ?

c# - 如何确定 LINQ 查询是 LINQ to SQL 还是 LINQ to Objects?

c# - LINQ 连接两个表

c# - 10000000个整数相加时为什么在ArrayList和List中赋值时间相同?

c# - 实现智能搜索/模糊字符串比较

javascript - Asp.net MVC 中的 jquery 验证错误 - 无法获取属性 'call' 的值 : object is null or undefined