Retrieve model list passed by ajax through FormData

1

I am sending an image, along with a model in which it contains a list of integers.

But I can not recover when I enter the Action. I can retrieve the image, field1 and field2, the field fieldList is left blank.

HTML

<input type="file" id="profilePic" name="file" value="Browse">

JS

var data = new FormData();
var files = $("#profilePic").get(0).files;

data.append("Image", files[0]); 
data.append("grupo[campo1]", "A");
data.append("grupo[campo2]", "B");
data.append("grupo[campoLista]", "1,2,3");

Ajax

$.ajax({
    type: "POST",
    dataType: "JSON",
    url: '/Home/Index',
    contentType: "application/json; charset=utf-8",
    data: data,
    contentType: false, // Not to set any content header  
    processData: false, // Not to process data  
    success: function(response) { 
   },
    error: function() { alert('A error'); }
}); 

Action

[HttpPost]
 public ActionResult Index(Grupo grupo){

var parCampo1 = grupo.campo1;
var parCampo2 = grupo.campo2;
var parCampoLista = grupo.campoLista;

if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{

    var pic = System.Web.HttpContext.Current.Request.Files["Image"];

    if (pic != null)
    {
        Session["ImgPath"] = "~/Content/Uploads/" + pic.FileName;
        string path = Server.MapPath("~/Content/Uploads/");
        pic.SaveAs(path + pic.FileName);
    }
}
 }

Model

public class Grupo
{
    public string campo1 { get; set; }
    public string campo2 { get; set; }
    public List<int> campoLista { get; set; }
}
    
asked by anonymous 28.11.2018 / 20:40

1 answer

1

The problem is here:

data.append("grupo[campoLista]", "1,2,3");

You are passing as a string and not as an array.

So I understand that formData.append does not support JSON, so my previous example did not work using JSON.stringify (). Try this:

var campoLista = [ "1", "2", "3" ];
let formData = new FormData();

jQuery.each(campoLista, function(key, value) {
    formData.append('campoLista['+key+']', value);
});

console.log(campoLista); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
28.11.2018 / 21:05