how to send array to API which contains image and other data in .net core

When I am passing a single object like below then it is working as per below image

[HttpPost]
public async Task<ActionResult> Post([FromForm] MyModel Details)
{
}

enter image description here

but when I am passing the List of the object to API then it is not working. option to upload a file is not visible. and if I entered any values in the array then also I am getting count 0 for details.

 [HttpPost]
 public async Task<ActionResult> Post([FromForm] List<MyModel> Details)
 {}

enter image description here

I want to pass the List of images and descriptions to API. How can I achieve it?

Thanks in advance!


Solution 1:

You need custom model binding for the list model . Here is a similar demo:

custom model binding code:

public class MetadataValueModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
            throw new ArgumentNullException(nameof(bindingContext));

        var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (values.Length == 0)
            return Task.CompletedTask;
        var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };

        var deserialized = JsonSerializer.Deserialize(values.FirstValue, bindingContext.ModelType, options);

        bindingContext.Result = ModelBindingResult.Success(deserialized);
        return Task.CompletedTask;
    }
}

Add the model binder to the model class:

public class MasterDTO
{
    public string Comments { get; set; }
    public IFormFile File { get; set; }        
    public List<DetailDTO> Details { get; set; }

    public MasterDTO()
    {
        this.Details = new List<DetailDTO>();
    }
}

[ModelBinder(BinderType = typeof(MetadataValueModelBinder))]
public class DetailDTO
{
    public Int64 ElementId { get; set; }

    public double LowerLimit { get; set; }

    public double HigherLimit { get; set; }

    public string Status { get; set; }

    public string UserAuthorization { get; set; }

    public DateTime? AutorizationDate { get; set; }
}

controller/action

        [HttpPost]
        public async Task<IActionResult> CreateProjectLimit([FromForm] MasterDTO masterDto)
        {
            //...

            return Ok();
        }

enter image description here

enter image description here

You can just use postman to pass the list of images and Descriptions to API

enter image description here enter image description here