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?