如何將ajax請求中的formdata數組發送給mvc操作

[英]How to send Array with the formdata in ajax request to mvc action


I was trying to send array with the form data to an action with Ajax request but whenever I do I receive both the form data and the array empty

我嘗試用Ajax請求將表單數據發送到一個動作,但無論何時我接收到表單數據和數組為空。

$scope.SubmitForm = function () {
        var sLangs = $("#supportedLanguages").data("kendoMultiSelect").value();    

        var formdata = new FormData($('#frmAppSettings').get(0));

        alert(formdata.SelectedLanguages);

        var data = new FormData(document.getElementById("frmAppSettings"));
        $.ajax({
            type: "POST",
            url: "/AppMenuMaker/AppSettings",
            data: JSON.stringify({ AppSettingsView: formdata, SelectedLangs: sLangs }),
            processData: false,
            contentType: false,
            success: function () {

            }
        });
    }`

I have my action as following

我的行動如下

    [HttpPost]
    [Authorize]
    public ActionResult AppSettings( ApplicationSettingsViewModel AppSettingsView, int[] SelectedLangs)
    {

    }

Any help ?

任何幫助嗎?

1 个解决方案

#1


1  

FormData is a set of name/value pairs representing form controls and their values, and is sent as multipart/form-data, You cannot stringify() it and/or send it with separate objects. You need to append name/value pairs to it.

FormData是一組表示表單控件及其值的名稱/值對,作為多部分/表單數據發送,不能對其進行stringify()和/或使用單獨的對象發送。您需要向它添加名稱/值對。

If the element with id="supportedLanguages" is inside the form with id="frmAppSettings", then your code

如果id="supportedLanguages"的元素在id="frmAppSettings"的窗體中,那么你的代碼就是這樣

var formdata = new FormData($('#frmAppSettings').get(0));

will correctly add the values of the <select> to the FormData object. If not, then you need to append each value in the array, for example

將正確地向FormData對象添加

var formdata = new FormData($('#frmAppSettings').get(0));
$.each($("#supportedLanguages").val(), function(index, item) {
    formdata .append('SelectedLangs', item);
});

and then the ajax options need to be

然后ajax選項需要是

$.ajax({
    type: "POST",
    url: '@Url.Action("AppSettings", "AppMenuMaker")', // use @Url.Action() to generate your url's
    data: formdata,
    processData: false,
    contentType: false,
    success: function () {
    }
});

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/10/30/72a329ab4f738b3dd5fc34dd82b13db3.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com