如何在Ajax请求中将带有FormData的数组发送到MVC动作 [英] How to send Array with the formdata in ajax request to mvc action

查看:141
本文介绍了如何在Ajax请求中将带有FormData的数组发送到MVC动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将包含表单数据的数组发送到具有Ajax请求的操作,但是每当我收到表单数据和数组均为空时,

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

$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是一组代表表单控件及其值的名称/值对,并以multipart/form-data的形式发送,您不能stringify()且/或与单独的对象一起发送.您需要在其上附加名称/值对.

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.

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

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

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

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

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

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

,然后需要ajax选项

and then the ajax options need to be

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

这篇关于如何在Ajax请求中将带有FormData的数组发送到MVC动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆