【问题标题】:Kendo Upload file is sending null in the controller when i send other values as parameters当我发送其他值作为参数时,Kendo Upload 文件在控制器中发送 null
【发布时间】:2016-11-21 12:12:33
【问题描述】:

情况是这样的: 我有一个表单,当我单击提交按钮时,它正在发送带有剑道上传控件的文件,并且控制器的方法操作正在使用 HttpPostedFileBase 的参数中接收该文件。

这是我的 HTML 代码:

@using (Html.BeginForm("ConfirmarOposicion", "Gestion", FormMethod.Post, new { @id = "Frm-login", role = "form", @class = "form-horizontal" }))
{
    @(Html.Kendo().Upload()
        .Name("files")
    )

    <button class="btn btn-success" type="submit" id="confirm" >Confirm</button>
}

这是我的控制器:

public async Task<ActionResult> ConfirmarOposicion(IEnumerable<HttpPostedFileBase> files)
{
    // Here the parameter files is not null..
}

到目前为止一切正常。问题是当我尝试将更多值作为参数发送到控制器的同一方法中时。 我要发送的其他值是一个数组,另一个是一个数字。 我尝试在 javaScript 中使用 ajax 发送这两个值。

这是我尝试发送另外两个值时的 javaScript 代码:

$("#confirm").click(function () {
        var numMarca = $("#numMarca").val()
        var idsToSend = [];
        var grid = $("#Grid2").data("kendoGrid")
        var ds = grid.dataSource.view();
        for (var i = 0; i < ds.length; i++) {
            var row = grid.table.find("tr[data-uid='" + ds[i].uid + "']");
            var checkbox = $(row).find(".checkbox");
            if (checkbox.is(":checked")) {
                idsToSend.push(ds[i].DescMarca);
                idsToSend.push(ds[i].IntencionOposicion = 1);
            } else {
                idsToSend.push(ds[i].DescMarca);
            }
        }

        $.ajax({
            url: '@Url.Action("ConfirmarOposicion", "Gestion")',
            data: { ids: idsToSend, marca: numMarca },
            type: 'POST',
            dataType: "json",
            success: function (data) {

            }
        });

当我单击提交按钮时,我在发送输入文件的同一控制器中发送这两个值。

这是我现在的控制器:

public async Task<ActionResult> ConfirmarOposicion(IEnumerable<HttpPostedFileBase> files, string[] ids, string marca)
{
    // here the array ids and the value of marca is not null, but the parameter files it is null

}

这就是我遇到的问题。 我需要在控制器的相同方法操作中发送所有这些值。 我该怎么做?

【问题讨论】:

  • 所以你的意思是说在你添加了其他参数之后你不再接收文件了?
  • 是的,文件现在是空的。
  • 给了你我的答案。

标签: javascript jquery ajax asp.net-mvc kendo-upload


【解决方案1】:

问题:是用这行代码data: { ids: idsToSend, marca: numMarca }, 您正在手动构建一个只有两个参数的数据对象,而不是处理上传的文件,因此文件数据丢失。

解决方案:构建一个FormData 对象,然后将所有需要的数据(包括您上传的文件)填充到其中,并将该对象发送到服务器。

var formData = new FormData();
var file_data = $('#files')[0].files; // for multiple files if only single file use $('#files')[0].files[0] and skip the loop.
for(var i = 0;i<file_data.length;i++){
    formData.append("file_"+i, file_data[i]);
}    
formData.append('ids', idsToSend);
formData.append('marca', numMarca );

$.ajax({
    url: '@Url.Action("ConfirmarOposicion", "Gestion")',
    data: formData ,  // pass the formData object to server.
    type: 'POST',
    processData: false,
    contentType: false,
    dataType: "json",
    success: function (data) {

    }
 });

注意:$('#files') 获取您的文件控件,kendo 语法中的 .Name("files") 将文件控件的 id 设置为 files

编辑:我在 ajax 选项中添加了 processData: false,contentType: false,致谢this answer

将 processData 设置为 false 可以防止 jQuery 自动将数据转换为查询字符串。请参阅the docs 了解更多信息。

contentType 设置为false 是必须的,否则jQuery will set it incorrectly

【讨论】:

  • 现在文件不再为空,marca 也不再为空,但现在控制器中的数组 ID 为空。我放了一个警报(idsToSend)并且数组不是空的,只有当我在控制器中收到作为参数时。
  • 尝试用JSON.stringify(idsToSend) 代替idsToSend 并告诉我结果
  • 你的意思是这样吗? formData.append('ids', JSON.stringify(idsToSend));它仍然发送空值。我不知道方法的参数是否必须是这样的:public async Task ConfirmarOposicion(IEnumerable files, int numMarca, string[] ids) {...}。我做错了什么?
  • 嗯不确定拥有List&lt;string&gt; 怎么样。但是string[] 也必须工作
  • 我添加了 processData: false 和 contentType: false 并且它仍然在控制器中发送 null 数组。
【解决方案2】:

使用 rawFile 获取正在上传的实际文件。就我而言,每个文件都会触发 onUpload

// JavaScript
function setupUpload() {
    // this example, I use filetemplate to prompt the user for file attributes
    $("#fileOrderDocuments").kendoUpload({
        async: {
            saveUrl: "/Order/ValidateUploadDocuments",
            autoUpload: false
        },
        template: kendo.template($('#fileTemplate').html()),
        multiple: true,
        upload: onUpload,
        validation: {
            allowedExtensions: [".pdf"],
            maxFileSize: 25194304
        },
        success: onSuccess,
        select: onSelect
    });
}

function onSelect() {

}

function onSuccess(data) {
// triggered after each file is uploaded
}

    function onUpload(e) {
    // expect exactly 1 file since async upload will be triggered for each file
        if (!e.files || e.files.length != 1) return;
    
        var formData = new FormData();
        formData.append("files", e.files[0].rawFile);  // use rawFile to access file
        formData.append("orderId", orderId);
    
        $.ajax({
            url: "/Order/UploadDocuments",
            data: formData,
            type: 'POST',
            processData: false,
            contentType: false,
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    };
    
    // .Net Core Controller - Order Actions
    [HttpPost]
    public ActionResult UploadDocuments(IEnumerable<IFormFile> files, int orderId)
            {
                if (files != null && orderId > 0)
                {
                    foreach (var file in files)
                    {
    _documentService.SaveDocument(file, orderId);
                    }
                }
    
                return Json(Ok);
            }

// Kendo template in cshtml Razor page to customize file upload

<script id="fileTemplate" type="text/x-kendo-template">
    <div class="row m-0">
        <span class='k-progress'></span>
    </div>
    <div class="row m-0 w-100">
        <div class="col-1 p-0">
            <span class="k-file-extension-wrapper top-0">
                <span class="k-file-extension">pdf</span>
                <span class="k-file-state"></span>
            </span>
        </div>
        <div class="col-5">
            <span class="k-file-name-size-wrapper">
                <span class="k-file-name">#=name#</span>
                <span class="k-file-size">#=size# bytes</span>
            </span>
        </div>
        <div class="col-5">
            <span id="selectOrderType">
                <div>Select Document Type:</div>
                <div>
                    <select class="js-doc-type">
                        <option value="1">Unsigned Document</option>
                        <option value="2">Signed Document</option>
                    </select>
                </div>
            </span>
        </div>
        <div class="col-1 p-0">
            <strong class="k-upload-status float-right">
                <button type="button" class="k-button k-upload-action" aria-label="Remove">
                    <span class="k-icon k-i-close k-i-x" title="Remove"></span>
                </button>
            </strong>
        </div>
    </div>
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 2011-07-03
    • 1970-01-01
    相关资源
    最近更新 更多