ajaxasp.net-corebase64croppie

How can I retrieve FormData (HtmlFormElement) data from Javascript in Razor PageModel?


I'm trying to send a base64 string to my Razor PageModel using ajax. The base64 string is the result of a Croppie result. Any help would be greatly appreciate. I've tried the following ways:

1) Creating a FormData form and sending that to my PageModel:

        var f = new FormData();
        f.append('s',base64)

        $.ajax({
            url: "?handler=SaveIcon",
            data: f
        });

Result:

        jquery.js:8463 Uncaught (in promise) TypeError: Illegal invocation
        at add (jquery.js:8463)
        at buildParams (jquery.js:8450)
        at Function.jQuery.param (jquery.js:8483)
        at Function.ajax (jquery.js:9073)
        at ChangeProfilePhoto:205

2) Passing the base64 string directly through ajax:

        $.ajax({
            url: "?handler=SaveIcon",
            data: { 's': base64 }
        });

Result: URI Too Long

3) Sending the base64 string through post:

        var token = $('input[name="__RequestVerificationToken"]').val();
        var headers = {};
        headers['__RequestVerificationToken'] = token;

        var f = new FormData();
        f.append('s', base64);

        $.ajax({
            headers: headers,
            url: "?handler=SaveIcon",
            method: "POST",
            data: f,
            contentType: false,
            processData: false
        });

Result: 400 Bad Request.


Solution

  • You need to set processData and contentType parameters to false

    var f = new FormData();
    f.append('s',base64)
    
    $.ajax({
        url: "?handler=SaveIcon",
        method: "post",
        data: f,
        contentType: false,
        processData: false
    });
    

    In order to pass antiforgery token via headers use default header name (if not configured other) RequestVerificationToken (without leading underscores)

    var headers = {
        RequestVerificationToken: token
    };
    

    Or you can pass it as FormData as well

    var f = new FormData();
    f.append('s',base64);
    f.append("__RequestVerificationToken", token);