Pass Array of Javascript objects to PageMethod

时光总嘲笑我的痴心妄想 提交于 2019-12-05 21:11:25

ASP.NET AJAX will automatically deserialize that for you if you use a DTO. Something like this on the server-side would match the JSON array you're sending in:

public class PeopleAndCarsDTO
{
  public int id { get; set; }
  public string name { get; set; }
  public string car { get; set; }
}

public static bool SaveData(List<PeopleAndCarsDTO> items) {...}

I figured out what the problem was. I was wrapping the array in quotes before sending it in as part of the $.ajax call so it was being treated as a string instead of an array.

            $.ajax({
                type: "POST",
                url: "<%= Response.ApplyAppPathModifier(Request.Path) %>/UpdateAcademicItems",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: "{'items': **'**" + $.toJSON(items) + "**'**}",
                success: function(data) {
                    if(false != data.d) {
                        alert('we did it');
                    } else {
                        alert ('flop');
                    }
                },
                error: function() {
                    alert('Failed to save Program Items');
                }
            }); 

@Jared the passed object is a JSON array. You can use json sharp to process it on server side. Here is a nice post about converting json array to C#.

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