Home > Software engineering >  How to send multiple images through ajax and receive them through the view model?
How to send multiple images through ajax and receive them through the view model?

Time:01-29

Suppose I have this ViewModel

public class AlbumViewModel
{
    public string AlbumDescription { get; set; }
    public List<FormFile> CuteImages { get; set; }
    public List<FormFile> BadImages { get; set; }
}

This form

<form id="AlbumForm" method="POST" enctype="multipart/form-data">
    <input type="text" name="AlbumDescription" />
    <input type="file" name="CuteImages" multiple/>
    <input type="file" name="BadImages" multiple/>
    <button type="button">Send</button>
</form>

This Javascript

$("button").click(function () {
    let form = document.getElementById("AlbumForm")

    $.ajax({
        type: "POST",
        url: "Album/Add",
        contentType: false,
        processData: false,
        data: new FormData(form)
    });
})

And this Album Controller

[HttpPost]
public IActionResult Add(AlbumViewModel viewmodel)
{
    var description       = viewmodel.AlbumDescription; //OK
    var filesFromHeaven   = viewmodel.CuteImages;       //null
    var filesFromHell     = Request.Form.Files;         //OK
    ...
}

I can get the images from the request but they appear null in the viewmodel.

The description is in the viewmodel, any properties other than the files are loaded.

I need the files to come from the viewmodel cause then I can use the cool data-annotation things to validate everything.

Does anyone know what could be missing?

CodePudding user response:

You need change FormFile to IFormFile in the model like below:

public class AlbumViewModel
{
    public string AlbumDescription { get; set; }
    public List<IFormFile> CuteImages { get; set; }
    public List<IFormFile> BadImages { get; set; }
}
  •  Tags:  
  • Related