Upgrading from Asp.Net Core 2 to .Net 6 caused issues with XMLHttpRequest for me

Hello everyone, I recently upgraded my ASP.Net Core 2 MVC app to .Net 6, and ever since then, I've been experiencing a strange issue. The XMLHttpRequest responses I receive are always empty, showing "{}" or [{},{},{},{}] for arrays, even though the backend is actually sending data.

For example, consider the controller method TestLoad that returns a simple class TestClass. When I debug and break on the return line, the value returned seems fine (refer to this image for debug info): backend

public class TestClass
{
   public int id = 0;
   public string title = "Title";
   public bool active = false;
}

public JsonResult TestLoad()
{
   TestClass testClass = new TestClass();
   testClass.id = 10;
   testClass.title = "Yeah man!";
   testClass.active = true;

   JsonResult jsonRes = Json(testClass);
   return jsonRes;
}

However, when I check the frontend, I see an empty object being received, not undefined or null, but truly an empty object (check this image for debug info): frontend

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200) {
            var dt = JSON.parse(xmlhttp.responseText);
            if (dt == 'err') {   
                alert('error');
            }
            else if (dt !== null) {                    
                alert(dt.title);                    
            }                
        }
        else {
            alert(xmlhttp.status);
        }
    }
}

ldwait(false, false);
xmlhttp.open("GET", rv + "ajxGame/TestLoad", true);
xmlhttp.setRequestHeader('Cache-Control', 'no-store');

xmlhttp.setRequestHeader("Content-Type", "application/json");

xmlhttp.send();

I would greatly appreciate any help or insights into why this could be happening. My code remains unchanged, only the migration from .Net Core 2 to .Net 6 has taken place.

Thank you in advance!

Answer â„–1

One way to enhance this code is by introducing a response type and updating the event listener to use onload instead of onreadystatechange.

    xmlhttp.responseType = 'json';

    xmlhttp.onload = () => {
        console.log("load - "+ JSON.stringify(xhr.response));
        var data = xhr.response;
       
    }

Answer â„–2

Are you utilizing Razor pages in your Asp.net core 6 application?

If that's the case, the issue may lie in how you are calling your method. When making post requests, ensure you call from the client using ?handler=TestLoad, and on the server, confirm the method name is OnPostTestLoad().

By default, get requests are disabled and need to be enabled. Check out this Microsoft Warning Message

For more information, refer to this link on Microsoft docs


Another potential issue could be in how you return your class. Try returning it as a JSON object instead.

return new JsonResult(new {objClass: testClass});

Then, on the client side, access your class as an object property

let objClass = result.objClass;

Answer â„–3

It turns out that my mistake was simply forgetting to include { get; set; } on each property of TestClass in the backend code! Surprisingly, it worked fine without it in .Net Core 2, but now it seems to be a requirement in .Net 6

public class TestClass
{
   public int id {get; set;} = 0;
   public string title {get; set;} = "Title";
   public bool active {get; set;} = false;
}

Shoutout to those who made an effort to provide a solution!

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

Issue with ReactJS: onChange event does not function properly when value is changed using jQuery

This is the reactjs code I am working with: <input name="date" id="date" value={this.state.listManage.date} onChange={this.handleForm} type="text" /> When I manually type in the input field, the onChange function works ...

How to include a javascript file in a different file and compile it using Node.js

For running my practice JS files, I rely on Node. As an example, I use node bts.js. In order to implement a queue, I decided to install Collections by using the command npm install collections --save. You can also see this reflected in the hierarchy shown ...

Can a function be activated in JavaScript when location permission is declined?

Background: Following up on a previous question regarding the use of getCurrentPosition and async functions. I am currently working on The Odin Project and attempting to create a basic weather application. My goal is to include a feature that automatically ...

I'm facing an issue with binding keyboard events in Vue - any suggestions on how to resolve

Hello everyone! I'm a newcomer to the world of Vue. Recently, I encountered an issue with keyboard-event binding that has left me puzzled. Let me share the relevant code snippet below: ...other code... <template v-for="(ite ...

What is the best way to delete a specific date from local storage using Angular after saving it with a key

I'm attempting to clear the fields in my object (collectionFilter) from local storage using localStorage.removeItem('collectionFilter'). All fields are removed, except for the date fields. Please note that I am new to JavaScript and Angular. ...

What is the best method for injecting a factory dependency into an angular controller?

Situation:- I have a factory named testFactory. Up until now, I was defining my controller like this: app.controller('testCtrl',function($scope,testFactory) { testFactory.Method1(){ //working fine} } However, before minimizing the file, I def ...

Tips for removing null or empty values from a JSON string

I have a certain Model that looks like this: public class DataClass { public string Name { get; set; } public string Address { get; set; } public string ContactNo { get; set; } } Attempting to convert it into a Json request using the followin ...

Decoding a formatted string

Here is a string that needs parsing: const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");' The goal is to generate a JSON structure like this: [{id: 'a', map: 'b'}, {id: 'foo', map: 'bar&a ...

Setting up PhpStorm for Global NPM module resolution

I'm in the process of developing a WordPress plugin, and the directory path I'm focusing on is: wp-content/plugins/pg-assets-portfolio/package.json I currently have the NodeJS and JavaScript support plugins installed (Version: 171.4694.2 and V ...

Transmitting a Custom JS Object via Vue Router

Stuck! I’ve been hitting my head against the wall for hours trying to figure this out... Technologies Utilized: Vue (v3.0.0) Vue-Router (v4.0.0-0) Bootstrap (v5.1.1) The Objective: I have two pages (Home.vue, MetaUpdate.vue) and one component (Docum ...

Controller data is being successfully returned despite breakpoints not being hit

While working with knockout Java-script, I encountered a perplexing issue. I have an API call to a controller which has several methods that are functioning correctly. However, when I set a break point on a specific method, it never gets hit. Strangely, da ...

Tips for avoiding the exposure of full user models in the jade template

As I work on the login functionality of my project, I'm utilizing express, passport-local, and mongoose. My code includes a series of routes: module.exports = function (app) { app.get('/', function (req, res) { res.render(' ...

Displaying or concealing list elements in Angular 6

I am working on a simple Angular app that displays a list of items. I want the behavior to be such that when the first item in the list is clicked, its description (card) should be displayed. And, if the second item is clicked and its description is displa ...

Instructions for applying a border style to a dynamically generated table using jQuery

I'm currently working on adding CSS to a table that is generated dynamically when a button is clicked. The function that is triggered on the click event includes the following jQuery code to create the dynamic rows: $("#employeDetail").append('& ...

Test the adjustment of the parameter value passed to a function within the Controller through unit testing

I need to verify if the passed variable is being modified within a function parameter. It's important that the variable itself undergoes a change. For my unit tests, I am utilizing Karma and Jasmine. In my Controller code snippet: angular.module( ...

The div's width shifts upon reaching the top of the page

Creating a blog site example and trying to lock the position of a div once it reaches the top of the page. Utilizing materialize.css for this task. <div class="row"> <div class="col m8 s12"> <!-- content goes here --> < ...

Encountered an issue with reading the property childnotes of null during data retrieval using ajax in PHP

Hello, I am encountering an error while trying to fetch data using ajax. The error message is "Cannot read property 'childNodes' of null". Can anyone help me identify what might be wrong with my code? I have created a form to search for data with ...

Exploring HTML5 video playback in AngularJS

When I use this code: <video id="video" class="video-js vjs-default-skin" controls width="640" height="264"> <source src="http://localhost:3000/files/public/photos/Let-her-go.mp4" type='video/mp4' /> <p class="v ...

The disappearing act of the Show/Hide Button in Sencha Touch 2.3.1: what's the

I'm running into an issue with my sencha touch app. Here is the container I have defined: { xtype: 'container', text: 'SOMETHING', height: '15%', width: '15%', ...

Firefox fails to render SVG animation

Currently, I'm attempting to incorporate this unique animation into my website: http://codepen.io/dbj/full/epXEyd I've implemented the following JavaScript code in order to achieve the desired effect: var tl = new TimelineLite; tl.staggerFromTo ...