简体   繁体   中英

Ajax with formData dose not bind child's array of objects in asp.net controller

Hi I am trying to send files and some object in ajax call, using form data

here is my ajax call

$.ajax({
   type: "POST",
   url: "/Post/SharePost",
   processData: false,
   contentType: false,
   headers: getAjaxHeaderWithToken(),
   dataType: "json",
   data: getDataToPost(),
});

here is my getDataToPost() method

function getDataToPost() {
    var dataToPost = new FormData();
    for (var i = 0; i < savedPictures.length; i++) {
        var savedPictureToPost = { PictureId: savedPictures[i].PictureId};
        dataToPost.append("vm.SavedPictures[" + i + "]", JSON.stringify( savedPictureToPost));
    }
}

here is my controller

[HttpPost]
[ValidateAntiForgeryTokenOnAllPosts]
public ActionResult SharePost(SharePostVM vm, IEnumerable<HttpPostedFileBase> unsavedPictures)
{

}

and here is my SharePostVM

public class SharePostVM : BasePostVM
{
    public SharePostCategories SharePostCategories { get; set; }

    [Required]
    public decimal? Price { get; set; }

    [Required]
    [Display(Name = "Available Date")]
    public string DateAvailableFrom { get; set; }

    public IEnumerable<PictureVM> SavedPictures { get; set; }
}

As you can see in my controller, I need to send files as well, but I just exclude the method for making it simple. Basically, I need to send files and object with an array of object. I can bind files and the property of SharePostVM like price and DateAvailableFrom by appending like dataToPost.append("vm", "priceValue"), but I can't bind the SavedPictures in SharePostVM. How can I bind them? I know I can retrieve from Request on server side but I just want to know if i can bind them. I have also tried without JSON.stringfy() but it still does not work..

Thanks guys

Try like this:

var pictureId = savedPictures[i].PictureId;
dataToPost.append("SavedPictures[" + i + "].PictureId", pictureId);
// ... and so on if you want to bind other properties than PictureId

Also in the getDataToPost function that you have shown in your question there's no return statement but I guess this is just a typo here and in your actual code the function returns a value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM