2

我使用 PageMethods 对象在 asp.net 中调用代码隐藏方法。我可以发送和接收字符串、int 等参数。但我必须向 codeBehind 发送一个 javaScript 对象。如何解析参数并从 codeBehind 获取数据?我想我必须使用 JSON 解析器,但我想知道是否有一种简单的方法,或者 .net 框架是否有 Json 解析器(或类似 JSON)?

    <script type="text/javascript" language="javascript">
        function test(idParam, nameParam) {
            var jsonObj = { id: idParam, name: nameParam };

            PageMethods.testMethod(jsonObj,
                function (result) { alert(result) });
        }
    </script>
    [WebMethod()]
    public static string testMethod(object param)
    {
        int id = 1;//I must parse param and get id
        string name = "hakan"; //I must parse param and get name

        return "Id:" + id + "\n" + "Name:" + name + "\n" + "Date:" + DateTime.Now;
    }
4

1 回答 1

1

试试这个(你可以添加 System.Collections.Generic 作为 using 子句来清理它):

[WebMethod()]
public static string testMethod(object param)
{
    System.Collections.Generic.Dictionary<String, Object> Collection;
    Collection = param as System.Collections.Generic.Dictionary<String, Object>;

    int id = (int) Collection["id"];
    string name = Collection["name"] as String;

    return "Id:" + id + "\n" + "Name:" + name + "\n" + "Date:" + DateTime.Now;
}

[编辑] 更简单:

// using System.Collections.Generic;
[WebMethod()]
public static string testMethod(Dictionary<String, Object> Collection)
{       
    int id = (int) Collection["id"];
    string name = Collection["name"] as String;

    return "Id:" + id + "\n" + "Name:" + name + "\n" + "Date:" + DateTime.Now;
}
于 2012-10-15T13:28:53.693 回答