简体   繁体   English

带有formData的Ajax不会在asp.net控制器中绑定子对象的对象数组

[英]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 嗨,我正在尝试使用表单数据在ajax调用中发送文件和某些对象

here is my ajax call 这是我的ajax电话

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

here is my getDataToPost() method 这是我的getDataToPost()方法

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 这是我的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. 我可以通过附加诸如dataToPost.append(“ vm”,“ priceValue”)之类的文件来绑定文件和SharePostVM的属性,例如price和DateAvailableFrom,但是我不能在SharePostVM中绑定SavedPictures。 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.. 我也尝试过不使用JSON.stringfy(),但仍然无法正常工作。

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. 同样在问题中显示的getDataToPost函数中,没有return语句,但我想这只是一个错字,在您的实际代码中,该函数返回一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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