将Javascript对象数组传递给PageMethod [英] Pass Array of Javascript objects to PageMethod
问题描述
以下是这种情况:我想迭代一个带有输入控件的表,收集值然后将它们提交给ASP.Net PageMethod以将数据保存到数据库中。我有所有的集合,但我得到一个错误,字符串无法转换为字典。
Here's the situation: I would like to iterate through a table with input controls, collect up the values and then submit them to an ASP.Net PageMethod to save the data to the database. I have the collection all figured out, but am getting an error that the string can't be converted to a Dictionary.
所以我最终得到这样的东西传递使用以下签名的方法
So I end up with something like this being passed to a method with the below signature
[
{ 'id': '383840923', 'name': 'fred', 'car':'honda' },
{ 'id': '243', 'name': 'joe', 'car':'honda' },
{ 'id': '4323423', 'name': 'paul', 'car':'honda' },
{ 'id': '38384234230923', 'name': 'ted', 'car':'honda' },
]
public static bool SaveData(Dictionary<string, object>[] items) {...}
我知道如果正确声明我可以来回传递全类对象,ASP.Net将为我处理转换,但我不需要整个类通过,只有几个属性。
I know that I can pass whole class objects back and forth if properly declared and ASP.Net will handle the conversions for me, but I don't need the whole class being passed, only a couple of the properties.
编辑:我正在使用Jquery将帖子发回服务器。
I'm using Jquery to do the post back to the server.
我在这里做错了什么?
What am I doing wrong here?
推荐答案
我弄清楚问题是什么。我在将数组作为$ .ajax调用的一部分发送之前将数据包装在引号中,因此它被视为字符串而不是数组。
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');
}
});
这篇关于将Javascript对象数组传递给PageMethod的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!