如何使用 ajax 请求中的表单数据将数组发送到 mvc 操作

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

我试图将带有表单数据的数组发送到带有 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 () {

            }
        });
    }`

我有如下操作

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

    }

有什么帮助吗?

FormData 是一组 name/value 对表示表单控件及其值,并作为 multipart/form-data 发送,您不能 stringify() 它 and/or将其与单独的对象一起发送。您需要向其附加 name/value 对。

如果带有 id="supportedLanguages" 的元素位于带有 id="frmAppSettings" 的表单内,那么您的代码

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

将正确地将 <select> 的值添加到 FormData 对象。如果不是,则需要将每个值附加到数组中,例如

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

然后 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 () {
    }
});