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

What are some effective methods for troubleshooting unidentified JavaScript functions within Chrome's performance analyzer?

Currently, I am utilizing Angular 4 and incorporating numerous anonymous arrow functions (() => {}). I am curious if it is feasible to identify these functions in Chrome's performance analyzer without assigning them names. Below is an example of t ...

What is the best way to fetch information from an API using Angular5 with Material2 components?

Here are the 'table.component.html' and 'table.component.ts' files where I am pulling data from an API to display in a table. Below is the object received from the API: [ {position: 1, name: 'Hydrogen', weight: 1.0079, sym ...

What is the best way to automatically adjust the size of this HTML Menu to match the width of its

I am in the process of converting a Drupal 6 theme to Drupal 7 and I'm encountering some difficulties with this particular section. Below is the HTML code snippet: <ul id="nav" class=" scaling-active scaling-ready"> <li><a href="/demos ...

The drawback of invoking an async function without using the await keyword

Here is the code snippet containing an async function: async function strangeFunction(){ setTimeout(function(){ //background process without a return //Playing Russian roulette if ( Math.random() > 0.99 ) throw n ...

The underscore convention for defining members in Typescript allows for clear and concise

Let's talk about a class called Email class Email { private _from: string; private _to: Array<string>; private _subject: string; } When an email object is created, it will look something like this: { _from:'', _to:'&apo ...

What sets apart the process of installing AngularJS and AngularJS Core using NuGet?

I am curious about the difference between these two packages in my packages.config file. Would it be advisable to uninstall one of them? <?xml version="1.0" encoding="utf-8"?> <packages> <package id="angularjs" version="1.3.15" targetFr ...

Locating HTML snippets within a document

I am trying to extract all HTML <p>...</p> elements from a document. I have been attempting to use regular expressions (Regex) with the following pattern: Regex regex = new Regex(@"\<p\>([^\>]*)\</p\>" ...

Discovering user activity through rooms within SocketIO

My goal is to trigger an event when a user switches between online and offline status. The challenge arises from the fact that a user may have multiple tabs open, making it ineffective to track their connection status using on('connect') and on(& ...

The access to the HTTP response object is not possible: the property is not found on the Object type

I recently created a response object and assigned it to the "this" object. However, when I try to access the datacentersinfo property, I encounter an error stating that the property does not exist on type Object. Due to this issue, I am unable to generat ...

When incorporating "<" or ">" into a parameter value in Angular Translate and then showcasing it in a textarea with ng-model

In my Angular Translate string, I am using a parameter that can be in the form of <test>. However, when this translate is displayed in a textarea, it shows up as &lt;test&gt; instead of <test>. Is there a way to ensure it appears correc ...

Navigate to a different page in NextJs without causing a page refresh or altering the current state of the application

Recently, I encountered a challenge in my NextJS application while attempting to incorporate dynamic routes as endpoints on my server. Specifically, when accessing localhost:3000/register, the register.tsx file is loaded successfully. However, within one ...

"Are you in search of an open source sketchpad with flash or ajax

Looking to add a drawing component to a charity website for users to create simple sketches. The component should: Allow users to draw in black on a white canvas. Save the full drawing process to the server. Save the final image to the server. Replay th ...

Updating Vue 3 asynchronous data doesn't reflect changes when the local settings are modified

I have a dedicated external .js file designed to retrieve data from the backend depending on the website's locale. Check out the code snippet below: import { ref } from "vue"; export function fetchData(section, key) { // Making a GET requ ...

Is there a way to output several lines from a JSON file in print form?

I'm working with HTML code that displays multiple lines from a JSON file, but it only shows one line at a time. How can I modify the code to display all users' information? <!DOCTYPE html> <html> <head> <script> function ...

Shifting a division using insertAfter

Hey there! I'm having a bit of trouble using the insertAfter function. In each product in my store, I need to position an "add to cart" button after the price. This is the code I tried: <Script type="text/javascript" > jQuery(document).read ...

Disable the default page scrolling behavior when collapsing an accordion section in Bootstrap 4 framework

Incorporating a Bootstrap 4 accordion with an expanded body section that causes the content below to scroll up when collapsed. To address this issue, attempting to scroll to the top of the clicked header and prevent undesirable scrolling from the collapse ...

Generating and consuming XML data with swagger-node

As a newcomer to swagger-node (swagger-spec 2.0), I am looking to have my API consume and produce both XML and JSON as requested by the customer. Currently, I have only focused on the "producing" aspect of it. When it comes to producing a response, I am a ...

Configuring a Meteor.js application requires defining variable scopes for templates in order to manage

Is there a way to define a variable that is limited in scope to a specific template? I want this variable to be accessible by multiple helpers within the template, but not outside of it. For example, how can the game variable be shared between two templat ...

Modify a property of an object using the useState Hook, where the property name is dynamically retrieved from a variable

const [fee, setFee] = useState({newPatient:'',establishedPatient:''}) const field1='newPatient' const field2='establishedPatient' To modify the fee object properties, I am looking to dynamically assign ...

The process of sending parameters to an API in ReactJS: a guide

My objective is to target .....the values originating from login (can be anything)-> for example email:'[email protected]' password:'12345678' I am required to extract the username until "@" and use it as a username i ...