When using JSON.stringify, the parameter sent to the ASP.NET MVC Controller is found to be null

My current task involves fetching information through an MVC controller by sending a JSON object as a parameter.

The method within the controller looks like this:

public ActionResult GetLatestInfoLogs(InfoLogUserJson invoker, InfoLogUserJson affected) {
    // code
}

I have a model on the server side that appears as follows:

public class InfoLogUserJson {
    public int id { get;set; }
    public int personId { get;set;}
    public int customerId { get;set; }
    public int rootUserId { get;set; }
    public string ip { get;set; }
    public bool unknown { get;set; }
}

In addition, I have a client-side script structured in this manner:

var InfoLogUser = function () {
    this.id = ko.observable(0);
    this.personId = ko.observable(0);
    this.rootUserId = ko.observable(0);
    this.customerId = ko.observable(0);
    this.unknown = ko.observable(false);
    this.ip = ko.observable(null);
}

InfoLogUser.prototype = (function() {
     return {
          toJSON: function() {
            return {
                personId: this.getPersonId(),
                rootUserId: this.getRootUserId(),
                customerId: this.getCustomerId(),
                id: this.getId(),
                unknown: this.getUnknown(),
                ip: this.getIp()
             }
         }
     }
}());

Within a JavaScript view model, my attempt at integrating these components is as follows:

var infoLogUser = new InfoLogUser();
infoLogUser.personId(1234);

$.ajax({
    url: '/Whatever/GetLatestInfoLogs',
    data: {
        invoker: JSON.stringify(infoLogUser.toJSON()),
        affected: null
    },
    dataType: 'application/json; charset: utf-8',
    type: 'GET',
    success: function(_infoLogs) {
        alert('yay');
    }
});

Upon inspecting my network log, I observe the following Query String Parameters:

invoker:{"personId":1234,"rootUserId":0,"customerId":0,"id":0,"unknown":false,"ip":null} affected:

However, upon reaching the GetLatestInfoLogs method in the MVC controller, the invoker parameter consistently registers as null. If I omit the JSON.stringify from the ajax request, the invoker parameter is not null, but still lacks any assigned value.

I am currently puzzled by this behavior and would appreciate any insights or suggestions you may have regarding this issue. Thank you!

Answer №1

Give this a shot

$.ajax({
        url: '/CheckOut/RetrieveLogs',
        type: 'POST',
        data: {
            user: JSON.stringify(userLogs),
            item: null
        },
        contentType: 'application/json',

        success: function(_logs) {
            alert('Success!');
        }
    });

Improved Version

var data = {user: userLogs, item: null};
$.ajax({
            url: '/CheckOut/RetrieveLogs',
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',

            success: function(_logs) {
                alert('Success!');
            }
        });

Answer №2

There's no need for you to create your own .toJSON() method.

All you have to do is:

invoker: JSON.stringify(infoLogUser)

It's important to ensure that you specify the content type as:

contentType: 'application/json'

I've also observed that your data type should be:

dataType: 'json'

The complete call would then look like this:

    var infoLogUser = new InfoLogUser();
    infoLogUser.personId(1234);

    $.ajax({
        url: '/Whatever/GetLatestInfoLogs',
        data: {
            invoker: JSON.stringify(infoLogUser),
            affected: null
        },
        dataType: 'json',
        contentType: 'application/json',
        type: 'GET',
        success: function(_infoLogs) {
            alert('yay');
        }
    });

Update For it to be valid json, you must change invoker and affected to strings like this:

 data: {
         "invoker": JSON.stringify(infoLogUser),
         "affected": null
        }

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

Instructions on accessing crystalreport.rpt files within aspx.cs files

Is there a way to access the crystalreport.rpt file in aspx.cs files using any specific coding method? ...

Having trouble retrieving jQuery variables in PHP using POST method

I have a jQuery script in another processing.js file that is included in the HTML file containing the form. $("#1st_submit").on("click", function(event) { var ServiceType = $("#ServiceType").val(); var locality = $("#locality").val(); $.ajax( ...

JavaScript encountering issues when parsing a string that was serialized using Gson in Java

This question is unique and differs from this one as it specifically addresses the representation of JSON strings serialized from Java in literal form in JavaScript, with a focus beyond just double quotes. In my scenario, I am serializing a JSON object in ...

How can I pass a variable name as an argument in Vue?

I am exploring ways to create a method that can efficiently load and assign JSON files to dynamic variables. Despite my efforts, varA and varB are not being populated as expected: data() { return { varA: Array, varB: Array } }, ...

What is the best way to encode images for inclusion in a JSON array?

I have a task that involves the following: Connecting to Amazon S3 to retrieve an image (.jpg) or sound file (.m4a). Storing these files in an array of objects. Sending the array to a client. The files exist on S3 and can be accessed through a browser. ...

How can I extract the reference link of a hyperlink within a specific division and use it for an image?

I currently have a div containing an image and a link. Is it feasible for me to find the href of the link on page load and then apply it to the anchor tag of the image? I understand this may sound like an unusual request, but I'm just curious if it& ...

Numerous data retrieval commands within the componentWillMount lifecycle method

Initially, I utilized the componentWillMount() method to populate the articles property successfully by iterating over the values to display various images/text. However, I am now encountering an issue as I also need to use componentWillMount to populate ...

Dealing with JSON files on Android devices

What is the best way to manage a JSON response when a webservice directly returns a .JSON file and clicking the URL in a web browser triggers the download of the JSON file? ...

Node class in Javascript for objects

This is a question about working with node.js. Is there a way to retrieve the attributes of a class model in JSON or string format? For example: module.exports:{ attributes: { user_num: {type: "integer", primaryKey: true}, contact_id: {type: " ...

Encountering issues with receiving controller response in Spring MVC while utilizing ajax technology

I am facing an issue with making an Ajax call to a controller in Spring MVC 3 using Eclipse Kepler IDE. I have watched some tutorials on YouTube and created a project for learning purposes. I had a similar problem before when making an Ajax call to the con ...

Implementing Alloy-Script/Javascript in dynamically loaded JSP files

I have been loading various JSPs dynamically using an Ajax call, but after the JSP is loaded, none of the JavaScript inside seems to be working. I suspect this is because the script has not been parsed yet. To address this issue, I came across the "aui-pa ...

Is there a method for enabling GPT-3's "davinci" to engage in conversation with users via a bot on Discord by utilizing discord.js?

var collector = new MessageCollector(message.channel, filter, { max: 10, time: 60000, }) start_sequence = "\nAI: " retart_sequence = "\nHuman: " collector.on("collect", (msg) => { ...

Getting data before the Router is loaded following authentication with Angular 2+ - A comprehensive guide

I'm hoping this isn't a repeat. Within my login component, I have a feature that allows users to log in, which calls a service and retrieves a Token. Upon successful login, the token is saved to localStorage. Subsequently, I use the getUserData ...

Generate dynamic buttons on an ASP.NET webpage and trigger a click event for each button

I am interested in dynamically creating buttons on an ASP.NET page, and I have written some code to achieve this. Below is the code responsible for creating the dynamic buttons: List<string> category = new List<string>(); category. ...

Transferring data from an ASPX page to a PHP script using an HTML form and subsequently saving it into a MySQL database

Can data be passed from an ASPX form to a PHP form, and then stored in a MySQL database? ...

Enhancing Rails 3 with pre-processing functionality and inserting input fields prior to submitting an Ajax form

I have a situation where I need to trigger an AJAX form in Rails 3 using the .submit() method programmatically. However, before sending the request to the server, I need to perform some client-side logic on the form data. This logic involves adding hidden ...

What is the process of invoking a JavaScript function from Selenium?

How can I trigger a JavaScript function from Selenium WebDriver when using Firefox? Whenever I am logged into my website, I typically utilize this command in Firebug's Command Editor to launch a file upload application: infoPanel.applicationManager. ...

Assistance needed on how to fill a gridview with data from a database

Firstly, I'm curious if adding a data source in the designer is necessary or if the DataSource = reader will handle that. Secondly, how can I restrict it to the user's badge number entered on the source page? For example, when a user enters a 3-d ...

Automatically populate a text box with database content without the need to navigate away from the current page

I have multiple forms on a single page that need to be automatically filled out by retrieving a user's ID and populating the rest of the form fields with relevant information. Essentially, I need an autofill feature for the forms based on the RFID ent ...

Guide to merging two JSON objects

I have two JavaScript objects as shown below: const objOne = { "firstname": "xzxz", "lastname": "xzxzxzx" }; const objTwo = { "title": [ { "name": "foo", "ta ...