Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - FormData append item in array

 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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])
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...