简体   繁体   中英

json Array posting to mvc controller

I want to post JSON array to MVC controller through AJAX POST as:

 $.ajax({
                    type: 'POST',
                    data: json.stringify(totaldata),
                    traditional:true,
                    url: '/Builder/Save',
                    success: function () {
                        alert("Playlist saved successfully!!");
                    }
                })

and my controller code is have made array of one ViewModel & want to update those values as.

[HttpPost]
    public ActionResult Save(IList<ItemEditViewModel> data,long playlistid=0, string Title="")
    {




        for (int i = 0; i < data.Count; i++)
        {
            var pc = db.PlaylistContents.FirstOrDefault(x => x.PlaylistContentId == data[i].ID);
            if (pc == null)
            {
                pc = new PlaylistContent();
                db.PlaylistContents.Add(pc);
            }
            pc.ContentMetaDataId = data[i].MetaID;
            pc.PlaylistContentSequenceId = i + 1;
        }

 db.SaveChanges();
            return RedirectToAction("Playlist", new {ID=playlistid });

}

But the Object is set to null in Controller.

My ViewModel is as,

public class ItemViewModel
{
    public long ID{get;set;}
    public long MetaID{get;set;}
}

Try adding the content type in ajax call,

contentType : 'application/json',

By default ajax sends with content type application/x-www-form-urlencoded; charset=UTF-8 application/x-www-form-urlencoded; charset=UTF-8

Edit

also i dont know it this is a typo, json.stringify should be JSON.stringify

hope this helps.

 $.ajax({
                    type: 'POST',
                    data: {"data":json.stringify(totaldata)},//You missed the format
                    traditional:true,
                    url: '/Builder/Save',
                    success: function () {
                        alert("Playlist saved successfully!!");
                    }
                })

The Problem is solved & my application is working now properly. I have just done JSON.stringify() on array elements & not the whole ajax data for posting.

the code is as written below:

 var totaldata =  { data: data, playlistid: parseInt(playlistid), Title: Title };
                $.ajax({
                    type: 'POST',
                    data: { data: JSON.stringify(data), playlistid: parseInt(playlistid), Title: Title, deleted: JSON.stringify(deleted) },
                    traditional:true,
                    url: 'Save',
                    success: function (data) {

                        alert("Playlist saved successfully!!");

                    }
                })

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