Troubleshooting ASP.net core AntiForgeryToken problem: model not receiving bound data

Currently, I have a functioning project built on a booking system in asp.net core that integrates a google Timeline chart. The interactive element involves a modal popup, which displays a partial view for data input when the chart is clicked. Utilizing Javascript, a click event on the save button triggers the sending of data to the controller for validation. Subsequently, the validated data is returned to Javascript, where it is displayed in the modal popup. However, an issue arises when I implement the [ValidateAntiForgeryToken] attribute on the controller.

The relevant code sections are outlined as follows:


StartUp:

services.AddAntiforgery(options => {
    options.HeaderName = "RequestVerificationToken";
});

Javascript:

(function() {
        var PlaceHolderElement = $('#PlaceHolderHere');
        
        PlaceHolderElement.on('click', '[data-save="modal"]', function(event) {
            event.preventDefault();
            var form = $(this).parents('.modal').find('form');
            var token = $("input[name='__RequestVerificationToken']").val();
            var actionUrl = form.attr('action');
            var sendData = form.serialize();
            $.ajax({
                type: 'POST',
                url: actionUrl,
                data: sendData,
            }).done(function(data1) {
                var newBody = $('.modal-body', data1);
                PlaceHolderElement.find('.modal-body').replaceWith(newBody);
                var isValid = newBody.find('[name="IsValid"]').val() === 'True';
                var isValid2 = newBody.find('[name="BookingFree"]').val() === 'True';
                if (isValid && isValid2) {
                    PlaceHolderElement.find('.modal').modal('hide');
                    location.reload();
                }
            })
        })

Controller:

[HttpPost]
public IActionResult EditBooking(BookingViewModel model) {

  if (ModelState.IsValid) {
    ... other code
  }
}

Introducing the [ValidateAntiForgeryToken] attribute to the controller requires a modification in the Javascript section:

data: {
    model: sendData,
    __RequestVerificationToken: token,
}

However, this adjustment leads to the model being empty upon validation. Using a string declaration for the model results in receiving a string output instead. Additionally, attempting to send the token in the headers fails the token validation process. The ultimate goal is to have the data properly stored in the model for the ModelState to reflect its validity.

Answer №1

1. By default, .serialize() includes the form data along with the __RequestVerificationToken value.

2. When using a form element with the method="post" attribute and tag helper, it generates a token input with

name="__RequestVerificationToken"
inside the form dynamically. However, if you specify the action attribute for the form like:
<form action="/url" method="post"></form>
, it will not generate the token input.

If you specify the action attribute, you must manually add the token input using @Html.AntiForgeryToken() in the form:

<form action="/url" method="post">
     @Html.AntiForgeryToken()
     //....
</form>

Here is a simple working demo you can refer to:

View:

<form asp-action="EditBooking" asp-controller="Home" method="post">
    <input asp-for="Name" />
    <input type="button" onclick="PostForm()" value="Post" />
</form>

@section Scripts
{
    <script>    
        function PostForm() {
            //var token = $("input[name='__RequestVerificationToken']").val();
            var actionUrl = $('form').attr('action');
            var sendData = $('form').serialize();
            console.log(sendData)
            $.ajax({
                type: 'POST',
                url: actionUrl,
                data: sendData,
            }).done(function(data1) {                                
            })
}
    </script>
}

There is no need to add the following code:

services.AddAntiforgery(options => {
    options.HeaderName = "RequestVerificationToken";
});

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

Transforming with Babel to create pure vanilla JavaScript

Our current development process involves working with a custom PHP MVC Framework that combines HTML (Views), PHP files, and included JS with script tags (including JQuery, Bootstrap, and some old-fashioned JS libs). During the development stages, we want ...

Error occurred during download or resource does not meet image format requirements

Encountering an issue when attempting to utilize the icon specified in the Manifest: http://localhost:3000/logo192.png (Download error or invalid image resource) from the console? import React from 'react'; import Logo from '../Images/logo1 ...

Troubleshooting issue with Django forms and JavaScript interactions

For the past day, I've been grappling with a particular issue and haven't made much progress. My setup involves using a django inline form-set, which displays all previously saved forms along with an additional empty form. To show or hide these f ...

Angular ng-if directive contains a specific class

I am trying to create a directive that will only be active when an element has a specific class. I have tried the following code: <feedback-analytics ng-if="$('#analyticTab').hasClass('active')"></feedback-analytics> Unfor ...

Conceal a dataLabel for a particular series in Highcharts

Currently, I am dealing with a chart that consists of 5 series - one as columns and the other four as lines with constant values. My dilemma lies in wanting to display dataLabels for only one of those series. Despite my efforts to activate/deactivate dataL ...

Issue with Ionic Native File: File.writeFile function - file is not being created and there is no callback response

I've exhausted all the different solutions I could find, but unfortunately, the file isn't getting saved and nothing seems to be happening. The callback functions aren't being called - neither success nor error. Here are the solutions I&apo ...

Adjust the position of the IMG to the left side

Struggling with some code and need some assistance: <script> function run() { document.getElementById("srt").value = document.getElementById("Ultra").value; } </script> <script> function ru ...

Is it possible to send an entire HTML table to the server and then update the database table with it?

Recently, I encountered an issue that has me stumped. Suppose I have a database table A with multiple columns and the server (PHP script) renders this data into an HTML table for the web client. Now, the challenge lies in allowing users to add/delete rows ...

Achieving the retrieval of all data can be done simply by utilizing the `echo json_encode($data);

I am trying to automatically update the user wall with new data from the database using a script that checks for updates every 15 seconds. Everything works fine when I only use one piece of data like $data = $row['description']; in the server.ph ...

Setting up multiple versions of npm application

Can I have multiple versions of npm installed for different projects on Windows 10, or are npm installations always global? I attempted to install different versions using https://github.com/marcelklehr/nodist, but it only affected the node version and no ...

Guide to changing the border color in a Material-UI TextField component styled with an outline design

To complete the task, utilize the Material UI outlined input field (TextField component from "@material-ui/core": "^4.12.2",) and apply a custom blue color style to it. Here is the outcome of my work: https://i.sstatic.net/lw1vC.png C ...

The module in Node.js is unable to be loaded

Dealing with a common problem here. Despite trying to reinstall npm, deleting node_modules files and package-lock.json, the issue persists. The console output is as follows: node:internal/modules/cjs/loader:1080 throw err; ^ Error: Cannot find module &apo ...

The Ajax Auto Complete function encounters an issue when attempting to assign a value to the TextBox

I have a Textbox that utilizes an Ajax Autocomplete function. The function is functioning correctly and retrieves values from the database, populating them in the TextBox as well. However, there is a button on the page that triggers a query, fetching som ...

Running JavaScript function from AJAX response containing both HTML and JavaScript code

For my first time using AJAX to prevent page refresh upon form submission, everything works flawlessly. The data is received in HTML form and placed into the designated div. However, I am encountering an issue with one of the JavaScript functions responsib ...

Updating Vue component property when Vuex store state changes: A step-by-step guide

As I work on developing a straightforward presentation tool using Vue js and Vuex to manage the app state, I am facing a challenge in implementing a feature that tracks changes in the presentation such as title modifications or slide additions/removals. Cu ...

Total the values of several items within the array

Here is the data I currently have: const arrayA = [{name:'a', amount: 10, serviceId: '23a', test:'SUCCESS'}, {name:'a', amount: 9, test:'FAIL'}, {name:'b', amount: ...

Ways to incorporate a loading feature in javascript, jquery, and php as it runs?

I have created a form that, when clicked on, returns a value within the page. Below is my form. When the form is submitted, it takes some time to process. I would like to display a loading message while the code is being executed. Here is my form: <ht ...

Merging two arrays together in JavaScript

Within my possession are two arrays: var g= [ { id: 36, name: 'AAA', goal: 'yes' }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { ...

Unable to fetch and save the generated PDF file using AJAX

I am currently using AJAX to generate a PDF based on JSP data using the iText library. The PDF is being generated on the server, but I am having trouble downloading it. I want to achieve this using jQuery AJAX because I do not want the JSP page to refresh ...

What is the best way to apply typography theme defaults to standard tags using Material-UI?

After reading the documentation on https://material-ui.com/style/typography/ and loading the Roboto font, I expected a simple component like this: const theme = createMuiTheme(); const App = () => { return ( <MuiThemeProvider theme={theme}> ...