Anish
Anish

Reputation: 3172

How to ajax post to a razor page handler?

The code looks like this

HTML:

    <form class="col-sm-6" name="log" >
       <div class="form-group row">
                    <label class="col-sm-3 col-form-label"></label>
                    <div class="col-sm-7">
                        <input name='logText' class="form-control">
                    </div>
                </div>    
                <div class="form-group row">
                    <div class="col-sm-7 offset-sm-3">
                        <button class="btn btn-primary" id="submit">Submit</button>
                    </div>
                </div>

            </form>

Javascript:

        document.forms['log'].onsubmit = () => {

            let formData = new FormData(document.forms['log']);
            fetch('?handler=log', {
                method: 'post',
                body: new URLSearchParams(formData)
            })
                .then(() => {
                    alert('Posted using Fetch');
                });
            return false;
        };
    </script>

C#:

    public void OnPostLog(string logText)
    {

    }

The ajax post goes through with a request that looks like this

Request URL: https://localhost:44345/?handler=log
Request Method: POST
Status Code: 400 
Remote Address: [::1]:44345
Referrer Policy: no-referrer-when-downgrade

However the server returns a 400. An ajax get works fine. A full page post to the handler works fine. Just not an ajax post to a handler. Is this capability even supported in Razor Pages?

Upvotes: 2

Views: 4457

Answers (2)

Anish
Anish

Reputation: 3172

The reason is, there is a __RequestVerificationToken embedded into the form. and this needs to be supplied during the ajax post. But for the token to be added to the form, you have to add method="post" the below to the form.

        <form class="col-sm-6" name="log" method="post" >

Source: https://www.talkingdotnet.com/handle-ajax-requests-in-asp-net-core-razor-pages/

Upvotes: 1

Jorge Solis
Jorge Solis

Reputation: 1806

Whenever I use fetch API, I use the FormData object as the body for the request instead of creating a new URLSearchParams object.

Hope it helps.

Upvotes: 0

Related Questions