Hakan Kara
Hakan Kara

Reputation: 443

What is the simplest way to pass javascript object to asp.net codebehind method and parse it?

I use PageMethods object to call a codebehind method in asp.net. I can send and receive parameters like string, int etc. But i must send a javaScript object to codeBehind. How can i parse the parameter and get data from codeBehind? I think i must use JSON parser but i wonder if there is an easy way, or if .net framework has Json parser (or like 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;
    }

Upvotes: 2

Views: 2184

Answers (1)

Steve Wellens
Steve Wellens

Reputation: 20620

Try this (you can add System.Collections.Generic as a using clause to clean it up more):

[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;
}

[Edit] Even simpler:

// 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;
}

Upvotes: 1

Related Questions