我在客户端有一个具有SettingName和SettingValue属性的javascript对象。
obj1.SettingName = "createdDate";
obj1.SettingValue = "10/07/2013";
obj2.SettingName = "arrayOfNames";
obj1.SettingValue = SomeArray; //An array of 5 strings
var settingsArray =new Array();
settingsArray[0] = obj1;
settingsArray[1] = obj2;
var settingsContainer = new Object;
settingsContainer.Settings = settingsArray;
$.ajax({
type: "POST",
url: "myURL",
data: { settings: JSON.stringify(settingsContainer)},
dataType: 'json',
success: function (data) {
//do something
}
});
public class Setting
{
public string SettingName { get; set; }
public object SettingValue { get; set; } //so this can hold multiple data types
}
public class SettingsContainer
{
public List<Setting> Settings { get; set;}
}
public ActionResult myURL(SettingsContainer settings) {
//Here, the value for SettingsContainer.Settings[1].SettingValue, which
should be Array[5] i.e. on the C# side, I expect to see Object[5],
is only {object}. I'm not sure what's going on.
Is my approach of handling this correct?
}
任何建议/帮助将不胜感激。感谢您!
答案 0 :(得分:0)
在服务器端方法上,您应该使用:
public ActionResult myURL(string settings) {
// deserialize the string to your object here;
}
但是你必须重新设计你的类,因为它们不受支持 javascript反序列化。
答案 1 :(得分:0)
尝试将'SettingValue'用作List<string>
或您期望的内容。您不能反序列化为object,因为反序列化器不知道对象是什么。
答案 2 :(得分:0)
尝试将ajax调用中的数据行设置为
data: "{ 'settings':" + JSON.stringify(settingsContainer)+"}",
(也许你可以避免使用SettingsContainer,只使用矢量或设置列表作为方法参数。)
以下代码可以帮助您解决问题。
代码隐藏:
public class helper
{
public List<DoubleText> prop { get; set; }
}
public class DoubleText
{
public string data1 { get; set; }
public object data2 { get; set; }
}
[WebMethod]
public static string work(helper example)
{
// do stuff here
return "ok";
}
的javascript / jquery的
var example = new Object();
example.data1 = 'value';
example.data2 = ['value1', 'value2'];
var example2 = new Object();
example2.data1 = 'value';
example2.data2 = ['value1', 'value2'];
var vector = new Array();
vector[0] = example;
vector[1] = example2;
var ex = new Object();
ex.prop = vector;
var test = "{ 'example':" + JSON.stringify(ex) + "}";
$.ajax({
type: "POST",
url: '/work.aspx/work',
data: test,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// stuff
},
error: function () { // other stuff}
});