Razor page fetch post method fails to include body in request

I am trying to send data from a page to the page model using AJAX (fetch API) POST request. I am able to reach the "OnPostTest" handler, but the variable "json" is null. Where could the issue be? Is it with my AJAX call or in the Razor page model method? Thank you.

Razor Page - Page Model

public JsonResult OnPostTest(string json)
{
    return new JsonResult(json);
}

JavaScript

async function getData() {
    fetch('./test/Test',
        {
            method: "POST",
            body: JSON.stringify({
                json: 'yourValue'
            }),
            headers: {
                'X-CSRF-TOKEN': document.getElementsByName("__RequestVerificationToken")[0].value,
                'Content-Type': 'application/json',
                Accept: 'application/json',
            }
        })
        .then(function (res) { return res.json(); })
        .then(function (data) { alert((data)) })
}

Razor Page

<form method="post">
    <button type="button" onclick="getData(this)" value="1">send</button>
</form>

----Edit----

JavaScript

async function getData() {
    fetch('./test/Test',
        {
            method: "POST",
            body: JSON.stringify(
                {
                    name: "myname",
                    value: 1,
                    date:new Date()
                }
            ),
            headers: {
                'X-CSRF-TOKEN': document.getElementsByName("__RequestVerificationToken")[0].value,
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            }
        })
        .then(function (res) { return res.json(); })
        .then(function (data) { alert((data)) })
}

Razor Page - Page Model

public JsonResult OnPostTest([FromBody] ViewModel json)
        {
            return new JsonResult(json.Name);
        }

        public class ViewModel
        {
            public string Name { get; set; }
            public int Value { get; set; }
            public DateTime date { get; set; }
        }

Answer №1

It is important to update the headers for proper backend communication. Since the backend expects a string, the body should only contain a string.

fetch('[url]',
        {
            method: "POST",
            body: JSON.stringify(
                 'yourValue'
            ),

            headers: {
                RequestVerificationToken: document.getElementsByName("__RequestVerificationToken")[0].value,
                'Content-Type': 'application/json',
                Accept: 'application/json',
            }
        })
        .then(function (res) { return res.json(); })
        .then(function (data) { console.log(data) })

Make sure to include [FromBody] in the page handler.

  public JsonResult OnPostTest([FromBody]string json)
    {
        return new JsonResult(json);
    }

Additionally, when passing a complex object like

{name:"myname",value:"5"}
, remember to serialize the object using JSON.stringify().

      body: JSON.stringify(
             name:"myname",
             value:"5"
        ),

The backend should use a complex object to receive the data properly.

    public JsonResult OnPostTest([FromBody]ViewModel json)
    {
        return new JsonResult(json);
    }
     
    public class ViewModel
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }

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

Display PDF file retrieved from the server using javascript

I am currently working on a web application using JavaScript, jQuery, and Node.js. I need to receive a PDF file from the server and display it in a new browser window. While I believe I have successfully received the file on the client side (the window sh ...

What are some ways to stop touch events from being handled by default?

My goal is to create a functionality similar to embedded Google maps where my component should respond differently based on the number of touches - allowing scrolling and zooming depending on the interaction. Specifically, I want to enable double touch nav ...

losing track of the requested parameters while working asynchronously with Firestore documents

Today is my first time experimenting with firestore and express. Here is the code snippet I am using: app.post('/api/create', (req, res) => { (async () => { try { console.log(req.body); //the above consle.lo ...

Creating a suggestion box within an HTML container using JavaScript

https://i.sstatic.net/Asi5r.pngI am currently working on a page where users can click on a word and receive a small suggestion box (like a tiny popup) to choose synonyms they prefer. Although I believe this can be achieved with JavaScript, I haven't ...

SuperAgent - Refresh the initial request with a new bearer token upon encountering unauthorized access

Issue: I encountered a problem while attempting to resend my original request using superagent. Here is some pseudo code that I came up with: function retryRequest({ params }) { return superagent.post(url) .set("Authorization", `Bear ...

Guide to Monitoring Object Property in a Vue Extension

Introduction Let's look at a basic plugin setup: import SomeObject from "./SomeObject"; /** * Simple Plugin Example... */ export default { install(Vue){ Vue.prototype.$someObject = Vue.observable(SomeObject); } } The g ...

Callback for Vue asynchronous components

<template> <div> <DynamicComponentA></DynamicComponentA> <!-- Display DynamicComponentB only after DynamicComponentA is loaded --> <DynamicComponentB></DynamicComponentB> </div> ...

Ensuring the validity of an HTML form by including onClick functionalities for additional form elements

I am working on a form that I put together using various pieces of code that I found online. My knowledge of HTML and JavaScript is very basic. The form includes a button that, when clicked, will add another set of the same form fields. Initially, I added ...

How can I display a customized component on a table based on the data object's value?

I am working on a custom Table component that I want to render based on an array of objects. The challenge is that I need the Table component to have two props: one for the data object and another for an array of objects, each containing a title and a func ...

Is there a way for me to update the placeholder text in my script from "CHANGE ME

Can anyone help me troubleshoot this code that's not working on my computer? I have a paragraph with the text CHANGE ME inside an element with the id "warning". I want to update this text when the login button is clicked, but it doesn't seem to ...

Guide to making a toggle button with a Light/Dark mode functionality

I have implemented a light/dark toggle button and now I want to integrate the functionality for switching between light and dark themes on my webpage. The switch should toggle the theme between dark and light modes when clicked. Some basic styling has been ...

How to Retrieve the Name of the Active Element from an Unordered List (<ul>) in ReactJS and Display it in the

I have a project where I am creating a long navbar specifically for mobile devices, and I am structuring it in an accordion style. Initially, the view will show the currently active link name. When the user clicks on this active link name, it expands below ...

Utilizing ASP.NET to call a JavaScript function

I am currently working on an ASP.NET page that is written in VB.NET and I am attempting to incorporate JavaScript into it. The goal is to take the value from one listbox and insert it into another listbox. One of the challenges I'm facing is the use o ...

Retrieve the identifier from the database by selecting the edit button within a jQuery DataTable

Whenever the delete button of a specific row is clicked, I need to retrieve the id of that row from the database. Once I have obtained the id, it needs to be sent to the controller to carry out the deletion of that row. I attempted to approach this issue ...

Does the JavaScript/userscript in Tamper Monkey work for ajax updates?

I have a great idea for a userscript on twitch.tv - it will hide streams with titles that match my blacklist. For instance, streams with Russian content often have '[RUS]' in the title, so I can add that to my blacklist and automatically hide the ...

Every time I try to call the event in jQuery for the second time, it fails to work

I am currently working on a website that features an image gallery powered by the jquery wookmark plugin with filtering capabilities. Recently, I integrated the colorbox plugin (which was provided as an example by wookmark) to enhance the user experience. ...

Creating a dynamic table in VuetifyJS by populating it with data in real-time

Dealing with a dynamically changing table columns can be tricky. This means that hardcoding the template for the table like this example won't work: <template> <v-data-table :headers="headers" :items="items" hide-actions cl ...

What is the method for determining the coordinate range in a three.js environment?

When developing a scene using html and javascript, incorporating a camera, renderer, and displaying the scene in a browser, how can one determine the visible range of the scene? In a specific scenario where only a 2-dimensional x/y scene with objects is b ...

Select a date from the JQuery calendar, verify it against the database, and display any events scheduled for that date

I am working with a jQuery calendar that stores the selected date in a variable named "X". My goal is to retrieve events stored on that specific date from the Database and display them. Can anyone provide some guidance? <div id="calendar"></div&g ...

When using React with Firebase, remember to specify the "to" property when using setState to avoid errors

Struggling to figure out what's going wrong after hours of trying. I'm new to React and would really appreciate your help. Initially, my state was an array of accommodations which I mapped over successfully. However, once I connected Firebase wit ...