0

When I send an array with AJAX (using JSON), my C# handler does not know how to handle the whole query (suddenly the querystrings combine with each other for some reason).

In this example I'm sending a very simple array to the server and the server says the querystring Name is null (but it is not null); Sending any request without the array works fine.

On that note, would appreciate if anyone could explain what the array looks like on the URL (if I wanted to send a request through the browser for example).

AJAX code:

    function btnClick() {
        var arr = new Array();
        arr[0] = "Hey";
        arr[1] = "Stackoverflow";
        arr[2] = "What's your name?";

        var jsonParam = { Name: "test", Pass: "123", Stuff: arr }
        $.ajax({
            url: "Test.ashx",
            type: "get",
            data: JSON.stringify(jsonParam),
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            async:false,
            success: function (response) { 
                alert(response.Name);
            }
        });
    }

Handler code:

public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "application/json";
    JavaScriptSerializer jss = new JavaScriptSerializer();



    string res = jss.Serialize(new UserInfo { Name = context.Request.QueryString["Name"], Pass = "pass" + context.Request.QueryString["Pass"], Stuff = new string[] { "1", "2" } });
    context.Response.Write(res);
}

1 Answer 1

1

You cannot get the json from querystring.

You can use this; You should install NewtonJsonfor JSonConvert from nuget. If you don't want that, you can use JavaScriptSerializer instead of that.

    protected object FromJsonToObject(Type t)
    {
        Context.Request.InputStream.Position = 0;
        string json;
        using (var reader = new StreamReader(Context.Request.InputStream))
        {
            json = reader.ReadToEnd();
        }

        return JsonConvert.DeserializeObject(json, t);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Up until I used arrays, I didn't have to deserialize anything. But okay, I realize arrays require deserialization now. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.