简体   繁体   English

使用表单数据将数组发布到使用 AJAX 的 C# WebAPI

[英]Post array using Form Data to C# WebAPI using AJAX

I want to post an array with some files using FormData to WebAPI however it is showing [Object%Object] on Webapi.我想使用 FormData 将包含一些文件的数组发布到 WebAPI,但是它在 Webapi 上显示 [Object%Object]。 Please help me out of this.请帮我解决这个问题。 Appricieted in advance.提前学习。 below is the code snippet:下面是代码片段:

        var arr = [];
        var table = $('#tblOptionType');
        var tr = table.find('tbody tr');
        tr.each(function (i, v) {
            if (i != 0) {
                var values = {
                    Options: $(v)[0].cells[0].firstElementChild.value,
                    IsCorrect: $(v)[0].cells[1].firstElementChild.checked,
                };
                arr.push(values);
            }
        });
        formData = new FormData();
        jQuery.each(jQuery('#QuestionImage')[0].files, function (i, file) {
                 formData.append('file-' + i, file);
        });                 
        formData.append("Options", arr);
        $.ajax({
            url: 'http://localhost:56892/api/Admin/Questions/AddQuestion',
            method: "POST",
            data: formData,
            contentType: false,
            processData: false,
            traditional: true,
            success: function (res) {}
            error:function(err){}
        });

Here is the string i am receiving on the WebAPI:这是我在 WebAPI 上收到的字符串: 在此处输入图片说明

You need to set contentType which is type of data you're sending, so application/json; charset=utf-8您需要设置contentType ,这是您发送的数据类型,因此application/json; charset=utf-8 application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8 application/json; charset=utf-8是常见的, application/x-www-form-urlencoded; charset=UTF-8 application/x-www-form-urlencoded; charset=UTF-8 , which is the default: application/x-www-form-urlencoded; charset=UTF-8 ,这是默认值:

$.ajax({
        url: 'http://localhost:56892/api/Admin/Questions/AddQuestion',
        method: "POST",
        data: JSON.stringify(formData),
        contentType: "application/json; charset=utf-8",
        processData: false,
        traditional: true,
        success: function (res) {}
        error:function(err){}
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM