Search code examples
javascript.netasp.net-mvcform-data

Convert object with nested arrays to FormData


I have this Object

{
  "Data1": 1,
  "Data2": "some string",
  "Data3": [
    {
      "ID": 0,
      "Name": "some name",
      "SomeArray": []
    },
    {
     "ID": 0,
     "Name": "another name",
     "SomeArray": [
       "DataA": 0,
       "DataB": "some data again"
     ]
    }],
  "Data4": "some string again"
}

The model which it will receive in the controller is this:

public class Data 
{
   public int Data1 { get; set; }
   public string Data2 { get; set; }
   public List<AnotherClass> Data3 { get; set; }
   public string Data4 { get; set; }
}

public class AnotherClass
{
   public int ID { get; set; }
   public string Name { get; set; }
   public List<DataList> SomeArray { get; set; }
}

public class DataList
{
   public int DataA { get; set; }
   public string DataB { get; set; }
}

The data that is to be set in Data3 is coming from a table where new inputs are retrieved from a modal popup and populated in the table. SomeArray data is coming from a dropdown which uses Select2 tool to set multiple choices in a dropdown.

The idea is that once the user clicks "Save", it will get all of the data, including those in the table and form this JSON object. From this object, I want to convert it into a FormData. However when it iterates into Data3, it doesn't convert it into an array of objects even if I stringify it. I've also tried this one Convert JS Object to form data but was unsuccessful.

Here's what I did so far:

var details = GetDetails(); // This contains `Data1`, `Data2` and `Data4`
var data3 = GetData3FromTable(); // This contains the list of `Data3`

var result = new FormData();
for (var key in details) {
   result.append(key, details[key]);
}

result.append("Data3", JSON.stringify(data3));
result.append("UploadFile", $("#upload")[0].files[0]);

// do ajax put or post after this line

Is there any jquery or javascript plugin that I can use to convert this object into FormData? Or is there any other way to convert it into FormData?


Solution

  • I found this link object-to-form-data where it converts any object, including nested arrays and upload files into FormData. However, there's just one change that needs to be done:

    From the link, replace objectToFormData(obj[property], fd, property); with objectToFormData(obj[property], fd, formKey);. This way, it sets the original property as the key. The output of the FormData when it is passed to the controller will be this:

    Data1: 1
    Data2: some string
    Data3[0][ID]: 0
    Data3[0][Name]: some name
    Data3[0][SomeArray]: []
    Data3[1][ID]: 0
    Data3[1][Name]: another name
    Data3[1][SomeArray][0][DataA]: 0
    Data3[1][SomeArray][0][DataB]: some data again
    Data4: some string again
    

    I hope this helps others!