Receiving null value with Web API POST using [FromBody]

Below is the code for my WebAPI in C#:

 [Route("")]
        [HttpPost]
        public void SaveTestRun([FromBody] object data)
        {
            inputResultsToDatabase(data);
        }

This is the ajax request I am making:

sendTestData() {
        this.get('ajax').request('/web/api/test/', {
            data: {"name":"John Doe", "age":18, "country":"United States of America"},
            method: 'POST',
            dataType: 'object',
            headers: {
                AjaxRequestUniqueKey: getAntiForgeryToken()
            }
        });
    },

When I check Google Developer Tools, the 'data' object is showing up as null. I have attempted to send the object as a string but am encountering the same issue.

Answer №1

The [FromBody] attribute is utilized to extract simple types from the request body.

Modify your Action method to accept a typed parameter

public class User {
    public string username { get; set; }
    public int age { get; set; }
    public string country { get; set; }
}

[Route("")]
[HttpPost]
public void SaveUserData(User info) {
    saveDataToDatabase(info);
}

Ensure that you are sending the data in the correct format

sendUserData() {
    var userData = {"username":"Jane Smith", "age":25, "country":"Canada"};
    this.get('ajax').request('/web/api/user/', {
        data: JSON.stringify(userData),
        method: 'POST',
        contentType: 'application/json',
        headers: {
            AjaxRequestToken: getAntiForgeryToken()
        }
    });
},

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

Encountering an issue in a Vue console where the $ref is returning null and prompting an error message

It's puzzling why I keep encountering a console error in Vue that says "cannot read null of a $ref". Despite having the correct HTML template and adding logic to the script tag as needed, I'm still facing this issue - Cannot read properties of nu ...

What is the best approach for dynamically accessing or rendering Children within an Angular Component?

I am facing an issue with reusing a component called wrapper with different child components. I found some helpful resources such as this SO question and this article. However, these only address cases where the child component is known in advance. In my s ...

AJAX for displaying a partial view or handling form validation errors

Struggling with implementing AJAX form processing in Rails? Let me break down my code and share my uncertainties: This is the snippet from my new.html.erb: <%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_na ...

Updating Website Content Using JavaScript Library or Asynchronous JavaScript and XML

Can jQuery be used to alter plain HTML text? For instance, suppose I have a time displayed as 18:00 in simple HTML text - is it feasible to implement a drop-down menu featuring options like +1, +2, +3 and so on, or -1, -2, -3 and so forth? This way, selec ...

Leveraging react redux in conjunction with next.js

Recently, I attempted to integrate Redux into my project using the next.js starter template from here. I successfully installed the next-redux-wrapper, however, I am having trouble locating the root file in the project. I followed the tutorial provided on ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

Tips for utilizing the "Sign In with Apple" feature through Apple JS

For implementing "Sign In with Apple" on a web platform using Apple JS, you can refer to the code example available at this link. Now, the query arises: where can I find the Client ID required for this process? I have tried using the app id identifier fro ...

Tips for correctly loading all elements on an HTML page before making CSS modifications

This question has been asked several times in the past. I am asking because when I used the on ready callback in jQuery, it did not change the placeholder text of my element "search_input". $( document ).ready(function() { $("#search_input").attr(' ...

The color of the button in HTML5 will remain constant and not shift

I have several buttons that function like radio buttons - only one can be selected at a time: <button id="btn-bronze" name="btn-bronze" type="button" class="blue-selected">Bronze</button> <button id="btn-silver" name="btn-silver" type="butt ...

How can you make the browser window scroll horizontally when a div is clicked using jQuery?

I have an image of an arrow inside a div. The div is positioned fixed in the bottom right corner of an extremely wide page. Is there a way to utilize jQuery to scroll the window 600px to the right each time the arrow is clicked? Also, can I detect when th ...

Executing a request via ajax using a radio button

Here is the input that I am working with: <input id="offline-42" onclick="javascript:checkoutSwitch(false);controlDivPayment('42');" name="payment" type="radio" value="offline-42" /> I am attempting to use ajax to add a product to the sh ...

"Experiencing difficulties deploying Firebase functions - Encountering an error message stating 'Cannot read property 'firebase-admin' of

I'm currently facing an issue during the deployment of my Firebase functions and I am seeking assistance to resolve it. While the deployment itself appears to be successful, I keep encountering the following error: Cannot read property 'firebas ...

Swipe to eliminate an element in Ruby on Rails

I am looking to implement a drag-and-drop delete feature on my website, similar to the recycle bin/trash function on Windows or OSX. Within my database, I have multiple objects represented by div elements using Ruby. While I know how to add drag functiona ...

Issue: [$injector:unpr] Provider not found: RequestsServiceProvider <- RequestsServiceFor more information on this error, please visit the website: http://errors.angularjs.org

Despite defining my service name in all necessary places, I am still encountering the error mentioned above. Below is my app.js: var app = angular.module('ionicApp', [ 'ionic', 'ngCordova', 'checklist-model' ]) ...

Import a large JSON file into either a MySQL or Oracle database

My team at work is responsible for supplying files to other services. These files typically range in size from 5MB to 500MB. We are considering using JSON instead of XML, but I am concerned about how our customers will be able to upload these files into th ...

Showing every piece of information line by line while uploading an AJAX CSV file

I have successfully parsed a CSV file using Papaparse, Jquery AJAX, and PHP. Now, I want to display the data line by line while the CSV file is being uploaded. Here is a snippet of my code: var xhr_file = null; $('#fileVariants').change(functio ...

Ways to fetch a JSON object using JavaScript

Currently, I am in the process of creating an HTML5 mobile application and utilizing jQuery to fetch a JSON file from this URL: . Here is the code snippet I used: var url='http://cin.ufpe.br/~rvcam/favours.json'; $.getJSON(url, function(data, s ...

What is the method for changing the Uint8Array object into a string?

I am encountering a similar issue as the one discussed in this post. I have read the solution provided, but I am having trouble grasping how to implement it. Are there any alternative suggestions? Here is my code snippet: var eccrypto = require("eccrypto ...

Is there a tool that can automatically arrange and resolve TypeScript dependencies, with or without the use of _references.ts file?

Currently, I am working on understanding the new workflow for "_references.ts" and I feel like there is something missing when it comes to using multiple files without external modules in order to produce correctly ordered ".js" code. To start with, I took ...

What is the best method for extracting specific information from an HTML webpage?

I am currently working on a project to create an MP3 song fetcher using WPF. The goal is to retrieve all the results from a webpage. However, I'm encountering issues where irrelevant data such as tags and non-downloadable links are being fetched. My ...