How to send a complex object with images to .net Core 8 server with javascript?

69 Views Asked by At

I'm trying to understand what is the best approach to sending the following object to a asp.NET 8 core web application. It is not a web api, just a normal website accepting a complex object input. Here is the object I am referring to:

public class ComponentModel
{
    public Guid Id { get; set; }
    public String SomeOtherValuesLikeThis { get; set; }
    public IList<ElementModel> Elements { get; set; } = new List<ProductComponentElementModel>();
}

public class ElementModel
{
    public Guid Id { get; set; }
    public String SomeOtherValuesLikeThis { get; set; }
    public IFormFile File { get; set; }
}

Normally I would do an ajax call which would allow me to send the complex object in form of json and that would look like this:

$.ajax({
    url: "/Some/Uri",
    type: "POST",
    data: myComplexObjectBuiltInJavascript,
    success: function (response) {
        //Do Some Logic
    },
    error: function (error) {
        //Throw an error
    },
    complete: function () {
        //Do Something
    }
});

However, because my ElementModel has a IFormFile I now have to send this object as a FormData (at least to my understanding, correct me if I am wrong). Something like this:

var data = new FormData();
data.append("Id", SomeId);

As the above is a linear build, I am failing to understand how do I turn this into a complex object, is this even possible? If not, what is another way I can send a complex object like above to my server with potentially multiple files.

If this is simply not possible or this is bad practice for some reason, how do you suggest that I send this complex data to my server?

So far I have thought of two approaches:

  1. Split into two types of calls, first call the parent to ensure the parent record is created, then second call for children (but this would result in many calls unless there is a way to do an array object that contains images and other fields).
  2. upload the complex object as is, then do a second call with images only and some way to reference where they belong.

The above ideas result in partial creation which I don't like, means a lot of cleanup if the subsequent calls fail. Right now I am leaning towards method 2 as a result of this as it feels less messy.

How should I approach this?

Note: If you provide an answer, please try to use code examples to help me better understand.

0

There are 0 best solutions below