Fetch API with ASP.NET Razor Pages without using a form

One of the least cumbersome methods for posting data without page refreshes

Asp.Net Razor Page methods requires the inbound data to be accompanied by a security token. Either in the header or within the dataset itself. When you use a form tag in Razor Pages the token is automatically injected into the request. Let say for example you have a single page app that sends different bits of data from different controls on the page. In such cases it may not be optimal to create several forms and hidden inputs throughout the page. Here is an example of how to use the Fetch API to send data to the server and receive a response without the use of a form tag. Im starting the snip out below by injecting the anti-forgery token.\ For the example's sake I added a control to submit the data and a container to display it.
@page
@model jgp.Areas.DevAdmin.Pages.BlogBinderSampleModel
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Antiforgery
<input type="hidden" id="RequestVerificationToken" value="@Antiforgery.GetAndStoreTokens(HttpContext).RequestToken" />
<button type="button" class="btn btn-primary" id="buttonSubmit">Send to server</button>
<div id="resultContainer"></div>
Below is three blocks of javascript: 1. the first attaches the click event listener to the button 2. next is the function that is executed after the Fetch API returns data form the server 3. lastly, the Fetch API call. I have it wrapped in a function so that other routines can easily implement it.
<script>
    // event handler to submit the data when the button is clicked
    document.getElementById('buttonSubmit').addEventListener('click',function () {
        submitFetch('SaveBlog',{'Title' : 'Test Post', 'Author': 'Gilbert'}, completeCallback);
    });
    
    // function to execute after the response data is received from the server
    function completeCallback(data) {
        document.getElementById("resultContainer").innerHTML = data;
    }
    // fetch function
    function submitFetch(method,data, fn) {
        const token = document.getElementById('RequestVerificationToken').value;
        // serverside method name 
        fetch('?handler='+method, {
            headers: {
                'Content-Type': 'application/json',
                'RequestVerificationToken': token 
            },
            method: 'POST',
            body: JSON.stringify(data)
        })
        .then(response => response.text())
        .then(data => fn(data))
        .catch(error => console.error('Error:', error));
    }
</script>
With this set up you get a very straightforward method submitting data to the server. Creating the submitFetch function makes it so easy you can call it in a one-liner as I did above.\ Another point worth mentioning, **the anti-forgery token is good for the life of the page**. It does not need to be renewed between requests. That is a huge win for single page app developers. I like code that is easy to read and easy to write. Let me know if you have any other methods for achieving the same result.
codeshorts avatar
Trevor 05 April 2025
  • ASP.NET Core
  • Single Page App
  • Razor Pages
  • JavaScript