Working with JSON in AJAX with Javascript and C# to handle array data

When attempting to send an array via AJAX using JSON, I am encountering a problem where my C# handler is unable to properly handle the query. It seems that the querystrings are merging together inexplicably.

In the scenario presented here, I am trying to send a basic array to the server, but the server is reporting that the querystring Name is null (even though it isn't); Sending requests without the array work as expected.

I would greatly appreciate it if someone could provide insight into how the array appears in the URL (in case I wanted to manually send a request through the browser).

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

Answer №1

Retrieving JSON data from the query string is not possible.

To achieve this, you can opt for using a library called NewtonJson to utilize the JSonConvert functionality available on NuGet. Alternatively, if you prefer not to use that library, you can make use of JavaScriptSerializer instead.

    protected object ConvertJsonToObject(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);
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Easily Update Your Div Content by Simply Clicking a Single Link/Button

I am in need of assistance here. My goal is to display dynamic content within a div. Below you will find the code I currently have: <script type="text/javascript"><!-- function AlterContentInContainer(id, content) { var container = documen ...

What is the process for calculating and determining the exact area the div should be released?

I am currently developing a drag-and-drop application using only Javascript. I have successfully implemented the dragging functionality, allowing elements to be moved randomly within the page. However, I now face the challenge of creating a drop zone with ...

Is there a way to retrieve the data instead of receiving an undefined result when making an asynchronous call?

subject in user.subjects = subjects below is undefined instead of being an array of subjects. Context: I am working with three database tables - users, subjects, and a relationship table between users and subjects known as users_subjects. The objective i ...

From converting JSON to Business Intelligence reports or tabular format

Currently, I am faced with a complex JSON structure that has 4 levels of hierarchy. I am in search of a reliable tool or solution that can help me convert this JSON object into a table format. So far, I have tried Power BI and other jQuery to table options ...

transferring information from the Quill text editor to the Node.js server

Is there a way to send data from Quilljs on the frontend to node.js on the backend? I've been searching for examples, but haven't found anything related to the backend. I tried reading the documentation for Quilljs, but I'm still struggling ...

Arranging Sequential Dates

Having a List<DateTime> dates; There is a class with the following properties: class NonWorkingDay { public DateTime Start; public int Days; } Seeking a clean approach to group them together. public List<NonWorkingDay> GetContiguousDa ...

What could be the reason why the initial console.log is failing to print?

Apologies for the oversight. The !== was a mistake that slipped past me before posting. Thank you for your understanding. I am a beginner in Javascript. I have written this function with winston: function setlogger(log_level = "warn", logfile, scree ...

Which element from the context menu has been selected?

We specialize in creating browser extensions for Chrome, Firefox, and Safari. Our latest project involves implementing context menus within the extensions that will appear when users right-click on any editable form element. I attempted to incorporate an e ...

Symbol reference in Wix remains unresolved

My current challenge involves creating an installer for a MVC4 application using Wix. Thankfully, I stumbled upon an example that demonstrates how to create such an installer for a MVC4 Application which can be found at this provided link However, during ...

Implement a dropdown menu in Vue.js using data fetched from an ajax request

I am looking to utilize ajax calls in conjunction with vue.js to dynamically populate the options for a drop-down menu. Here's an example of what I currently have: <select v-model="selected"> <option v-for="option in options" v-bind:valu ...

Having trouble with Google Maps Places API autocomplete feature; it's not functioning properly

My goal is to integrate the Google Maps Places API with a search box. To test jQuery autocomplete, I managed to make it work using this simple example: function bindAutocomplete() { var locationSearch = $("input#Location"); locationSearch.autocom ...

Tips for sending a JavaScript object to a Java Servlet

I'm facing a challenge with passing a JavaScript object to a Java Servlet. I've experimented with a few approaches, but nothing has worked so far. Below is the code snippet I've been working on: $.ajax({ url: 'TestUrl', d ...

What is the best way to return a collection of diverse items as a JSON object using a .NET web service?

Imagine having the following lineup of models: AnimalModel DogModel : AnimalModel CatModel : AnimalModel ElephantModel : AnimalModel The goal is to return a List as a JSON object in a web service... what would be the optimal approach? Co ...

What are the steps to switch to a root page after a successful sign-in with Ember-Auth?

After successfully implementing Ember-Auth using a pure token based approach, I am facing a challenge in redirecting users to the root of my app once they sign in. Although I know about actionRedirectable (refer to for details), since I am using a pure t ...

The JSON.Unmarshal function is not correctly decoding into the inner interface{} as expected

I am in the process of creating a new wrapper for the Telegram Bot API in Golang, as a way to enhance my learning experience. Within this project, I have defined a Response struct: type Response struct { Ok bool `json:"ok"` ErrorCode int64 `json:"erro ...

Creating a Yup field that is an object and making it required when another field is set to true in the validation process

Just getting started with Yup validation and I'm facing an issue. I am attempting to make certain fields required based on a condition. Specifically, I want the digital object to be required only if hasDigital is true; otherwise, it should be optional ...

Is there a way to retrieve data from a sealed JSON object using JavaScript?

The data is being fetched from the API and here is the response object: { "abc": [{ "xyz": "INFO 1", "pqr": "INFO 2" }, { "xyz": "INFO 3", "pqr": "INFO 4" } ] } We are lookin ...

Exploring the contrast of utilizing the `new Date()` function compared to Firestore's `new

I am developing a new app and need to calculate the time elapsed between the start and end of a run. When the run starts, I record a timestamp using the new Date() function in Firebase. (I opted for this over firestore fieldValue to avoid conflicts with o ...

Explanation on subtracting the row value from a textbox

Click here to view the image For instance: If I enter a value in the "USED(kl)" textbox, it should subtract that value from the corresponding row where "KILOGRAM/S" is located; Upon clicking the update button, only the specific row should be affected wh ...

Setting up Redis for session store in the right way involves a few key steps

I have been attempting to configure Redis Store in the following manner: var express = require('express'); var app = express(); ....... ....... var session = require('express-session'); var redis = require("redis").createClient(); var ...