FormData append item in array

喜欢而已 提交于 2019-12-28 06:44:23

问题


 public List<Region> Regions { get; set; }

in model called News.An Region Model is

public class Region
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public static Region Parse(DataRow row)
        {
            return new Region
            {
                Id = Database.GetInteger(row["Id"]),

                Name = Database.GetString(row["Region"]),


            };
        }
    }

in Javascript I am using AJAX post method with formdata. I want to set this region.

var regionList = [];
            if (selected === "region") {
                if (region.length <= 0) {
                    toastr.warning('Lütfen en az bir bölge seçin !!!');
                    return;
                }

                for (var i = 0; i < region.length; i++) {

                    var item = {
                        Id: region[i]
                    }
                    regionList.push(item);
                }
                console.log(regionList);
                formData.append("Regions", regionList);
            }

Code above in JS i wrote like this to set it

 public ActionResult AddByRegion(News item)
        {
            int refPortal = SessionRepository.GetPortalId();
            if(refPortal!=1)
                return View("List", NewsRepository.ListAll(SessionRepository.GetPortalId()));
            if (item == null
                || string.IsNullOrEmpty(item.Title)
                || string.IsNullOrEmpty(item.Content)
                )
                return Content(Serialization.JsonSerialize(new { Status = 400 }));

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

and code above i will get in controller. But it returns always 0 record although at least i choosed two region.

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

                contentType: false,
                processData: false,
                success: function(data) {
                    var result = JSON.parse(data);
                    if (result.Result === "SUCCEED") {
                        toastr.success('@Resources.Resource.Success_MediaAdd');
                        window.location.reload();
                        return;
                    }

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

                    toastr.error('@Resources.Resource.Error_Unexpected');
                    return;
                },
                beforeSend: function() {
                    waitingDialog.show('Wait...');
                },
                complete: function() {
                    waitingDialog.hide();
                }
            });

My Ajax method is above. Where am I making mistake ?

Thanks in advance.


回答1:


If your using FormData to send the data, you need to .append() each individual name/value to FormData. Since its a collection, you must include the collection indexer (which must be zero based and consecutive), for example

formData.append("Regions[0].Id", someValue);
formData.append("Regions[0].Name", someValue);
formData.append("Regions[1].Id", someValue);
formData.append("Regions[1].Name", someValue);

Since your doing this in a loop, you can use

for (var i = 0; i < region.length; i++) {
    formData.append("Regions[" + i + "].Id", region[i])
}



回答2:


 var regionList = [];
    for (var i = 0; i < region.length; i++) {
        var item = {
            Id: region[i].Id,
            Name : region[i].Name,
        }
        regionList.push(item);
    }

    regionList = JSON.stringify({ "item": regionList });//Here "item" name should match the parameter name in your Action method name in controller (item in your case.)

Then pass the regionList object to $.ajax as data.

 $.ajax({
            type: 'POST',
            url: '@Url.Action("AddByRegion", "News")',
            data: regionList,

            contentType: false,
            processData: false,
            ....
        });


来源:https://stackoverflow.com/questions/43385587/formdata-append-item-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!