简体   繁体   中英

Sending data to handler in .NET via Ajax. XML Parsing Error: no root element found

I have the following script which is executed in my UI.

metadata is a JSON object, which is passed into the function from elsewhere.

在此处输入图片说明

Dashboard.cshtml

<script>
    function sendToken(metadata) {
        $('#link-button').html('<i class="fas fa-circle-notch fa-spin"></i>');
        $.ajax({
            type: "POST",
            url: "Dashboard?handler=Token",
            headers: {
                "XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val()
            },
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(metadata),
            success: function(response) {
                $('#link-button').html('<i class="fas fa-success"></i> Account Connected Successfully');
            },
            failure: function(response) {
                $('#link-button').html('<i class="fas fa-success"></i> Failed To Connect Account');
            }
        });
    }
</script>

Handler in RazorPages (Dashboard.cshtml.cs):

public JsonResult OnPostToken() {

    MemoryStream stream = new MemoryStream();
    Request.Body.CopyTo(stream);
    stream.Position = 0;

    using(StreamReader reader = new StreamReader(stream)) {
        string requestBody = reader.ReadToEnd();
        if (requestBody.Length > 0) {

            // Get Public Token
            Console.WriteLine("Public Token: " + requestBody);

            // Create Badges

        }
    }

    return new JsonResult("");
}

Error:

在此处输入图片说明

What is going on here? Why can't I send the data to my handler for processing?

It looks like you are passing Json data, you need to deserialize it :

var myObj =  JsonConvert.DeserializeObject<youdatatype>(Request.Body)

What is the type of you data ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM