将javascript对象传递给asp.net代码隐藏方法并解析它的最简单方法是什么?

时间:2012-10-15 12:43:03

标签: asp.net json

我使用PageMethods对象在asp.net中调用codebehind方法。我可以发送和接收像string,int等参数。但我必须发送一个javaScript对象到codeBehind。我如何解析参数并从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;
    }

1 个答案:

答案 0 :(得分: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;
}