Issue with transmitting Razor form data to API controller using fetch or AJAX

I have created a basic razor web project and defined it as follows: in program.cs I added

builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

In the controller, this is what I did:

[Route("/api/[controller]")]
[ApiController]

public class BookController : ControllerBase
{

    [HttpPost("SimplePost")]
    public IActionResult SimplePost([FromForm] BookEntry entry)
    {
        var result = entry;
        return Ok();
    }

}

The class looks like this:

public class BookEntry
{
    public int BookId { get; set; }
    public string BookName { get; set; } = string.Empty;
}

And then on the view page,

@Html.AntiForgeryToken()
    <form id="bookform">
                    <div class="row">
                        <div class="col">
                            <label for="BookId" class="form-label">Book Id</label>
                            <input type="text" name="BookId" class="form-control" />
                        </div>
                        <div class="col">
                            <label for="BookName" class="form-label">Book Name</label>
                            <input type="text" name="BookName" class="form-control" />
                        </div>
                    </div>
                </form>
                <div class="row mt-5">
                    <div class="col position-relative">
                        <div class="d-grid gap-2 d-md-block position-absolute bottom-0">
                            <button class="btn btn-outline-secondary" id="search__btn"><i class="fa fa-search fa-fw"></i>Post Buton A</button>
                        </div>
                    </div>
                     <div class="col position-relative">
                        <div class="d-grid gap-2 d-md-block position-absolute bottom-0">
                            <button class="btn btn-outline-secondary" id="search__btn2"><i class="fa fa-search fa-fw"></i>Post Buton B</button>
                        </div>
                    </div>
                </div>

Where I create two buttons, so in the JavaScript code, I wrote the following :

 <script>
        $(function () {
            var url = "/api/book/simplepost";
            $("#search__btn").click(function (e) {
                var formData = $("#bookform").serialize();
                fetch(url, {
                    method: "POST",
                    body: formData,
                    contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
                })
                    .then(response => console.log("done"))
            });
             $("#search__btn2").click(function (e) {
                var formData2 = $("#bookform").serialize();
                $.ajax({
                    url: url,
                    type: "POST",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    headers:
                    {
                        "RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
                    },
                    data: formData2,
                    success: function (result, status, xhr) {
                        console.log(`success`);
                    },
                    error: function (xhr, status, error) {
                       console.log(`error`);
                    }
                }).always(function () {
                    console.log(`always done`);
                });

            });
        });
    </script>

When I click Post Button A which uses fetch, it goes to the simplepost function, but the entry parameter inside is empty. When I click Post Button B, the console displays a 400 error even though I have added the header. Can someone help me fix this issue?

Thank you

Answer №1

Utilize query data transfer:

 $("#search__btn").click(function (e) {
                var formData = $("#bookform").serialize();
                fetch(url+"?"+formData , {
                    method: "POST",
                })
                    .then(response => console.log("complete"))
            });

process:

[HttpPost("SimplePost")]
    public IActionResult SimplePost(BookEntry entry)
    {
        var result = entry;
        return Ok();
    }

Answer №2

If you've recently built an ASP.NET Core Web App, you may have encountered a situation where the auto-generated code fails to map the controllers in your program.cs file. Don't worry, your code is correct - all you need to do is add the following line to your program.cs.

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();
app.MapControllers();   // This specific line needs to be added

app.Run();

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

Setting model value in Angular 2 and 4 from loop index

Is it possible to assign a model value from the current loop index? I've tried, but it doesn't seem to be working. Any suggestions on how to achieve this? Check out this link for my code <p *ngFor="let person of peoples; let i = index;"& ...

"An error was thrown due to an illegal invocation while utilizing $.post, although $.ajax seems to be

I've been experimenting with FormData to send data to a different URL, but the code below doesn't seem to be working $("form").on("submit", function(e){ e.preventDefault(); var formData = new FormData(this ...

Styling elements with CSS

I've been attempting to align a button to the right of another button. The example above illustrates what I'm trying to achieve. I used Bootstrap to build it, which has a useful navbar feature for layout. However, despite my efforts to use right ...

The error message you are encountering is: "Error: Unable to find function axios

Can't figure out why I'm encountering this error message: TypeError: axios.get is not functioning properly 4 | 5 | export const getTotalPayout = async (userId: string) => { > 6 | const response = await axios.get(`${endpoint}ge ...

Displaying checkbox values with JavaScript

How can I display multiple checkbox values when checked in HTML code? Whenever I check a checkbox, I want its value to be shown alongside the previously checked values. Right now, my code only displays one value at a time. Any suggestions on how to achie ...

Loading external scripts prior to component loading in Vue.js

Within my Vue project, I have the need to fetch a script from a server location (e.g. https://myurl.com/API.js). This script contains a variable that I intend to utilize within my Vue component/view. The issue arises when I attempt to load this script usi ...

Discover the power of React Meteor, where reactive props and inner state work together

I am working with a component that utilizes the draft-js library for text editing. import React, { Component } from 'react' import { EditorState, convertToRaw } from 'draft-js' import { Editor } from 'react-draft-wysiwyg' imp ...

Exploring object key-value pairs using the 'for in' loop in JavaScript

Embarking on a project to develop a quiz in javascript, I am starting with an array that holds the questions as anonymous objects. var allQuestions = [{ "question": "Who was Luke's wingman in the battle at Hoth?", "choices": ["Dak", "Biggs", "Wedge", ...

What are some of the techniques for customizing the DOM generated by material-ui in ReactJS?

Is there a way to style the dynamically created DOM elements from material-ui? I'm currently using GridListTileBar, which generates a DOM structure like this for its title property. <div class="MuiGridListTileBar-title-29" data-reactid=".0.3.0.$3 ...

Tips for eliminating repetitive code in JavaScript

I have a jQuery function that deals with elements containing a prefix 'receive' in their class or ID names. Now, I need to duplicate this function for elements with the prefix 'send'. Currently, it looks like this: function onSelectAddr ...

Using jqGrid to load additional JSON data after the initial local data has already been populated in the

I encountered a specific issue: I have a compact form with four choices. Users can choose to fill them out or not, and upon clicking 'Ok', a jqGrid is loaded with data based on those selections. To accommodate dynamic column formatting, my servle ...

Can a single page be used to send email?

My PHP form is currently sending data to another page, and the layout does not look good. I want to keep the form on the same page so that when a user fills it out, the information is submitted without redirecting. If any of the inputs are empty, I would l ...

Simulating NextJS router triggers using Jest

I've been attempting to simulate NextJS router events using Jest. I came across a useful resource at NextJS router & Jest. The approach outlined there closely resembles mine. Unfortunately, the solution provided in that post is not yielding the d ...

Styling buttons with different colors using React onClick event.getSelectedItem() method

I am having an issue with adding a border when the class is set to "transportation active" in my React code. When I click on one of the icons, all of them become active instead of just the clicked one. This behavior is not what I want, as I only want the ...

Using React to trigger a child component's function upon clicking a tab

I need assistance with creating a React app that includes two tabs (Tab1, Tab2). When Tab2 is clicked, I want a message to appear in the console saying 'Function A is called'. Unfortunately, the code I have currently does not display the message ...

Update WooCommerce Mini-cart with ajax refresh

I'm having an issue with my custom plugin where everything is working properly, except for the fact that the mini cart is not updating after adding items. I have tried various methods to trigger a refresh, but so far nothing has worked. Below is a sni ...

Which library does stackoverflow utilize to showcase errors (utilizing Bootstrap popover for error help-block)?

Currently, I am using bootstrap's has-error and help-block classes to display validation error messages in my form. However, I find the error message display in Stackoverflow's Ask Questions Form to be very appealing. Are they using a specific js ...

angular-recaptcha: Adjusting language based on the website's language update

My website offers three different languages that users can switch between. The language switch functionality is implemented on the client side using JavaScript (AngularJS). I have integrated reCAPTCHA 2 into my website and now I need to update the languag ...

Adjust the color of each list item depending on an array of strings

Within my perspective, I possess a collection of different statuses. <ul> <li>FIRST_STATUS</li> <li>SECOND_STATUS</li> <li>THIRD_STATUS</li> </ul> To continuously update the statuses in my contr ...

Discover the way to utilize the java enum toString() function in jQuery

In my Java Enum class called NciTaskType, I have defined two tasks: Pnd Review Woli and Osp Planning. public enum NciTaskType { PndReviewWoli, // 0 OspPlanning, // 1 ; @Override public String toString() { switch (this) ...