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

Tips for extracting URL parameter values in React applications

Here is a component that allows for searching: import { ChangeEvent, useCallback, useState } from 'react'; export function SearchComponent() { const [searchValue, setSearchValue] = useState<string>(''); const updateSearchValu ...

What is the best way to incorporate my Switch component into my Table component as a distinct column, while also maintaining separate states for each component?

My journey into learning React.js has been exciting so far. However, I am facing some confusion when it comes to stateful components. Currently, I am utilizing Bootstrap tables for creating a table and successfully fetching data using GET requests. Additio ...

The specified variable will not be visible in the window object

I recently created a JavaScript code snippet that looks like this: let var1 = 1; window.var2 = 2; After running the code in the Chrome console, I entered window to inspect the global window object. Surprisingly, only the second variable appeared and the ...

Using JavaScript to dynamically write content to the document in the

What is the correct way to write the HTML break tag "<br>" in JavaScript without it causing a line break? I want the tag to be displayed as text. For example, "the break tag in html is ..." See below for an example of what I am looking for. <scr ...

Using jQuery Datepicker, showcase two distinct datepickers on a single page

Currently, I am utilizing the jQuery [Datepicker][1] on a website, but I am facing challenges when attempting to display two datepickers on the same page in different manners. The first one should only appear once you click the text box, and once a date i ...

Compare the precise value of $(window).height() to a specific scroll value

Initially, I retrieve $(window).height() and compare this height with the specific scroll value. $(window).scroll(function (event) { var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); console.log("window hei ...

JavaScript refuses to execute

I am facing an issue with a static page that I am using. The page consists of HTML, CSS, and JavaScript files. I came across this design on a website (http://codepen.io/eode9/pen/wyaDr) and decided to replicate it by merging the files into one HTML page. H ...

AngularJS NG-Grid displaying incorrect value for select cell

I'm working on creating a table with a column that needs to be selected based on a value received from the server. The server sends me 4 as the value, but the first option is always selected instead. $scope.lotteryOptions = { data: 'myDa ...

Imitate adjustment of orientation without the need to resize the browser window

Is there a way to simulate page portrait orientation on a PC browser without resizing the window? In my HTML code, I have a <div> element that displays content dynamically based on screen orientation. Is it possible to use JavaScript to trick this & ...

Transfer the contents from the text box field into the <p> tag

I know how to transfer text from one textbox to another in JS, but I'm interested in moving the text from a textbox to a paragraph. Can anyone explain how to achieve this? Thank you Update: Apologies for not being more specific earlier. I'm att ...

unable to respond when clicking an angularjs link

I'm facing an issue where I can't get a link to respond to click events in AngularJS. When I click on the anchor link, nothing happens. Here is a snippet of the AngularJS script: <script data-require="<a href="/cdn-cgi/l/email-protection" ...

I struggled to modify the image cropping code to specify a particular image

(I will attempt to explain my issue once again) I came across a script online which can be viewed at this link : Link However, I am having trouble modifying the code to suit my needs. The script currently starts working on image upload, but I want it t ...

Trouble initiating Jquery on a dynamically generated table

I am currently working on a project in ASP.Net where I need to dynamically build an HTML Table. I have implemented the ability for users to resequence rows in the table, but I'm facing issues with the delegate events I've written. Sometimes they ...

Stop users from being able to copy text on their smartphones' internet browsers

I am currently working on creating a competitive typing speed challenge using JavaScript. Participants are required to type all the words they see from a div into a textarea. In order to prevent cheating, such as copying the words directly from the div, o ...

Techniques for transferring PHP print_r arrays to Javascript

Array ( [0] => Array ( [sno] => 1 [name] => Sivamani [contact] => 750241378 [$city] => Madurai ) ) Array ( [1] => Array ( [sno] => 2 ...

What is the method to obtain the keycode for a key combination in JavaScript?

$(document).on('keydown', function(event) { performAction(event); event.preventDefault(); }); By using the code above, I am successful in capturing the keycode for a single key press. However, when attempting to use a combin ...

What is the best way to determine if certain rows of data have been successfully loaded when working with Ext.data.operation and an ajaxProxy?

Here is the provided code snippet: Ext.define('Book', { extend: 'Ext.data.Model', fields: [ {name: 'id', type: 'int'}, {name: 'title', type: 'string'}, {name: &apo ...

Give a radio button some class

<input id="radio1" type="radio" name="rgroup" value="1" > <label for="radio1"><span><span></span></span>1</label> <input id="radio2" type="radio" name="rgroup" value="2" > <label for="radio2"><span ...

When a menu item is clicked, apply a class and change the display property to

I currently have an HTML menu with a submenu structured as follows: <li id="item-3" class="menu-item has-children-3"> <a href="#" class="sf-with-ul"><span>Auto</span></a ...

Struggling with Creating Custom Validation Methods in JQuery

I'm currently implementing the JQuery validation plugin and have created a new method to check the availability of a name in the database. The PHP script is functioning properly, returning either 1 or 0 depending on availability. However, the method c ...