8

Hello I have a problem to post data to controller. Now I have one model below,

public class Media
    {
        public int Id { get; set; }
        public string Category { get; set; }
        public string Guid { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public List<int> Portals { get; set; }
        public string Lang { get; set; }
        public List<Folder> Folders { get; set; }

       }

Then I will post file and this model to controller. In View AJAX Side

var formData = new FormData();
            var totalFiles = document.getElementById("FileUpload").files.length;
            if (totalFiles === 0) {
                toastr.warning('Lütfen resim yükleyin.');
                return;
            }
            for (var i = 0; i < totalFiles; i++) {
                var file = document.getElementById("FileUpload").files[i];

                formData.append("FileUpload", file);
            }

            var itemFolder= {
                Id: refFolder
            }

            var folderss = [];
            folderss.push(itemFolder);

            var item = {
                Title: title,
                Description: desc,               
                Category: category,
                Portals: portals,
                Folders: folderss
            }
            formData.append("Title", title);
            formData.append("Description", desc);
            formData.append("Category", category);
            formData.append("Portals", portals);
            formData.append("Folders",folderss);


            $.ajax({
                type: 'POST',
                url: '@Url.Action("Add", "Media")',
                data: formData,

                contentType: false,
                processData: false,
                success: function (data) {
                    var result = JSON.parse(data);
                    if (result.Status !== 200) {

                        toastr.error('@Resources.Resource.Error_Unexpected');
                        return;
                    }

                    if (result.Result === "SUCCEED") {
                        toastr.success('Resim kaydedilmiştir.');
                        window.location.reload();
                        return;
                    } else {
                        toastr.error('@Resources.Resource.Error_Unexpected');
                    }

                },
                error: function (error) {
                    toastr.error('@Resources.Resource.Error_Unexpected');
                    return;
                }
            }); 

And i take this post data in controller like

public ActionResult Add(Models.Media item)
        {
            if (item == null
                || string.IsNullOrEmpty(item.Title)
                || string.IsNullOrEmpty(item.Category))
                return Content(Serialization.JsonSerialize(new { Status = 400 }));

            if (Request.Files.Count <= 0)
                return Content(Serialization.JsonSerialize(new { Status = 401, Result = "NO_FILE" }));

            return Content(Serialization.JsonSerialize(new { Status = 200, Result = MediaRepository.Add(item) }));
        }

I take all data without Folders attribute it comes null. How can I solve this problem? Thank u

  • Collection objects need indexers. But if you have generated you view correctly, then all you need is `var formdata = new FormData($('form').get(0));` to correctly serialize to your model (refer [how to append whole set of model to formdata and obtain it in MVC](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681)) –  Jan 20 '17 at 21:36

3 Answers3

22

Because Folder is a collection of objects, you have to add each one of them with an index.

var index = 0;
for(var pair of folderss){
    var folder = pair[key];
    formData.append("Folders[" + index + "].Id", folder.Id);
    index++;
}
Federico Alecci
  • 914
  • 6
  • 14
0
for (var i = 0; i != array.folderss; i++) {
    formData.append("Folders[" + i + "].Id", array[i].Id);
}
wasdoska
  • 41
  • 5
0

//asp c#

public class product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Color> Colors { get; set; }

}

public class Color
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
}

// javascript

var colorList=[];

const addColor=(item)=>{
    colorList.push({
        id:item.id,
        name:item.name,
        code:item.code
    })
}

const save=()=>{
    var data=new formData();
    data.append('Id', 1);
    data.append('Name', 'productName');

    colorList.forEach((item, i)=>
        Object.keys(item).forEach(key => 
            data.append(`colors[${i}].${key}`, item[key])
    ));
    ...
}