简体   繁体   中英

Sending Complex Objects to Controller with Ajax

I have an MVC application where I am trying to submit the form through an ajax call while also passing in another complex object. This means I am passing 2 complex objects back to the controller: the form data and an object array. The problem is the form data makes it to the controller fine if I set the contentType to "application/x-www-form-urlencoded" but the object array comes over as null. If I set the contentType to "application/json", the object array makes it to the controller just fine, but the form data is null. So I think I basically need to convert the form data to a json object. Here's what I've got:

ViewModel:

Public FOO foo
{
     public ObjectBar BarObject {get; set;}
     public string BarString {get; set;}
     // more properties
}

Controller:

[HTTPPost]
Public ActionResult Submit(Foo viewModel, OtherObject[] dataSet)
{
     //do stuff
}

View:

// bunch of fields

<script>

    function submitForm(e) {
        debugger;
        var dataSets = getGridData();
        var form = $("#formName").serialize();
        var data = JSON.stringify({ viewModel: form, dataSet: dataSets }); //this is close, need to convert form data to json

        return $.ajax({
            type: "POST",
            url: '@Url.Action("Submit", "Report")',
            data: data,
            contentType: 'application/json',
            processData: false,
        });
    }

    //some more javascript stuff
</script>

Searching around stack overflow, it seems like all I need to do to convert the form data to json is something like

var jsonForm = JSON.parse(JSON.stringify(form));

but for some reason that is not working, even if I just try to pass just jsonForm to the controller witrh just the viewModel parameter. Should I be using something else to convert, or am I just missing something?

With some help from this answer in stack overflow:

Convert form data to JavaScript object with jQuery

I found this statement:

$('form').serializeArray().map(function(x){this[x.name] = x.value; return this;}.bind({}))[0]

So I updated my code and wound up with this:

function submitForm(e) {
    debugger;
    var dataSets = getGridData();
    var form = $("#formName").serializeArray().map(function (x) { this[x.name] = x.value; return this; }.bind({}))[0];
    var data = JSON.stringify({ viewModel: form, dataSets: dataSets }); //this is close, need to convert form to json... now this works!


    return $.ajax({
        type: "POST",
        url: '@Url.Action("Submit", "Report")',
        data: data,
        contentType: 'application/json; charset=utf-8',
        processData: true,
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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