Recover Model List Passed by ajax through Formdata

Asked

Viewed 53 times

1

I’m sending an image, along with a model that contains a list of integers.

But I’m not recovering the moment you enter Action. I can recover the image, field1 and field2, while the field.

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; }
}

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.

From what I understand formData.append does not support JSON, so my previous example did not work using JSON.stringify(). Test this way:

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>

  • It still comes blank. however at the date.append is right, I did a check with: * for (var pair of data.Entries()) { console.log(pair[0]+ ', ' + pair[1]); } ? Now I have no idea why it doesn’t go there in the controller.

  • Check now with the edition I made.

  • Now yes! Thank you @George Wurthmann

Browser other questions tagged

You are not signed in. Login or sign up in order to post.