2

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

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

...Took me way longer than I hoped, but it's not your fault. I wanted to do this using an object with a list in it: var jsonListOfStrings = {"listOfTexts": [] }; and when I read it back in with C# I was trying to parse it using a cast to List<string> or string[], but it turns out you have to cast to object[] and then you can iterate through it. Hope that helps someone. Kudos.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.