0

我在客户端有一个具有 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 调用 -

    $.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?
}

任何建议/帮助将不胜感激。谢谢!

4

3 回答 3

0

尝试使用“SettingValue”作为List<string>或您期望的东西。您不能反序列化为对象,因为反序列化器不知道对象是什么。

于 2013-10-08T09:46:10.700 回答
0

在服务器端方法上,您应该使用:

   public ActionResult myURL(string settings) {
       // deserialize the string to your object here;
    }

但是您必须重新设计您的类,因为 javascript 反序列化不支持它们。

于 2013-10-08T06:34:36.997 回答
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}

            });
于 2013-10-08T12:01:33.250 回答