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

Troubleshooting Checkbox Problems on Internet Explorer 6

In order to have checkboxes generated dynamically for a pop-up window utilizing AJAX, I am using Javascript. Furthermore, when a button is clicked, a function needs to be executed that checks all the checkboxes before the pop-up appears. The web pages bei ...

Unravel a PySpark dataframe with certain columns represented as arrays of nested structures

I currently have a dataframe structured like this : root |-- first_name: string |-- last_name: string |-- details: array | |-- element: struct | | |-- university: string | | |-- subjects: struct | | | |-- subject1: string | | ...

I am facing an issue with uploading files to my designated directory through Node.js Multer

After creating a web service using node js and implementing a form with React interface that includes user information and file upload, I encountered an issue while attempting to save the file to the specified directory on the node js server using multer. ...

Is there a way for me to convert a JBuilder view into a JSON string format?

I'm currently utilizing JBuilder to create JSON output on my project. The data is being generated by an index.json.jbuilder file, but I am facing a challenge when trying to convert it into a string format. Despite attempting methods like @my_object.to ...

The JavaScript string in question is: "accepted === accepted && 50 > 100". I need to determine whether this string is valid or not by returning a boolean answer

I am developing a dynamic condition builder that generates a JavaScript string such as, tpc_1 === accepted && tpc_6 > 100 After the replace function, the new string becomes, accepted === accepted && 50 > 100 Now my challenge is to va ...

NodeJs Importing a File

Currently working with NodeJS, I have encountered a challenge. Is it possible to require a JavaScript file in Node similar to how we do in browsers? When using the require() method, I noticed that the JavaScript file called does not have access to global v ...

Having trouble retrieving text from an HTML form in Node.js using express, as the req.body object is coming up

Having trouble extracting text from an HTML form to build a basic text to speech functionality. Despite using an express server, the req.body is consistently empty when attempting to fetch the text. I've experimented with body-parser and adjusted the ...

Guide to accessing and utilizing environment-specific values during configuration stage

My goal is to deploy my web application across multiple environments. With Continuous Integration, I can automate the generation of a config.json file for each specific environment. This file will include important URLs that need to be used. { "baseUrl" ...

Overcoming Troublesome Login Input Box in Web

In an effort to streamline tasks in our office, I am working on automating certain processes. Specifically, this program is designed to log into our insurance company's website and extract information for payroll purposes. Below is the code snippet th ...

How to Modify the Data in a Dynamic Object within the Vuex Store in a Nuxt Application

Within my Vue/Nuxt project, I have implemented a form where users can add and update dynamic fields for calculating price offers. Upon loading the form, one field is created using the beforeMount lifecycle, with the option for users to add more fields as n ...

Modifying an HTML attribute dynamically in D3 by evaluating its existing value

I'm facing a seemingly simple task, but I can't quite crack it. My web page showcases multiple bar graphs, and I'm aiming to create a button that reveals or conceals certain bars. Specifically, when toggled, I want half of the bars to vanish ...

Having trouble calculating the number of days between two dates at this moment

I'm working with a code snippet that involves comparing two dates – a specified date and the current date. However, when trying to calculate the difference in days between these dates, I keep getting either 0 or an unexpectedly large number like "31 ...

Utilizing XML over JSON in Grape integration with Rails 3 on Heroku platform

While using Grape (https://github.com/intridea/grape) with Rails 3, I encountered an unusual issue. I have set json as the default output format in my API class and I am utilizing the as_json method to display the results. Here's a snippet from my /l ...

Is there a solution to resolving JSON version 1.7.5 and UTF-8 encoding issues?

I am facing issues with a report that covers models with spec tests. Here are the gems in my project: group :development, :test do gem 'factory_girl_rails', '3.4.0' gem 'rspec-rails', '2.11.0' gem 'guard- ...

jquery is unable to locate text

UPDATE: I have recently implemented a function that calculates and displays the length of a certain element, but it currently requires user interaction to trigger it: function check() { alert($("#currentTechnicalPositions").html().length); } After s ...

Refresh a specific portion of an HTML template following a successful AJAX request

I am facing a challenge in implementing a new feature and I'm unsure of the best approach to take. In my project, I utilize Django for backend logic and templating, as well as the Google Closure JavaScript library for frontend development. Here is th ...

Create a captivating sliding effect on Windows 8 using a combination of CSS and JavaScript

I believe that using css3 alone can achieve this effect, but I'm struggling with understanding properties like 'ease' in css3. This is the progress I have made so far: http://jsfiddle.net/kwgy9/1/ The word 'nike' should slide to ...

Utilize ModifyDOM to erase text triggered by selecting a radio button

I have created a form that includes four radio buttons along with a reset button to clear the form. When a radio button is selected, information is displayed using "displayText". I am looking to add an onclick handler to trigger a function that will delete ...

JavaScript- Tabbed Navigation with Lists as the Content

Currently, I am facing a frustrating issue in finding a suitable solution. My website uses tabs that utilize the UL, LI system, similar to most tab systems found in tutorials. The problem arises because the javascript on my site interferes with using the ...

Novice in AngularJS routing

Having trouble with my first AngularJS routing code. The error console isn't much help. Here is my HTML page: <body ng-app="myApp"> <div ng-controller="AppController"> <div class="nav"> <ul> <li> ...