0

I can't get ajax to transfer values to my asp.net razorpage handlers. It always receives null values on razorpage side. Otherway around it works and javascript isn't responding without errors.

The C# function "OnPost" gets called but has always null values as parameters.

What am I missing here? I looked at quite some examples and couldn't make it out. Am I missing something which has to be setup in the project? Please let me know if I should provide more code!

public class TestValues
    {
        public string test1 { get; set; }
        public string test2 { get; set; }
        public string test3 { get; set; }
    }

public class Conf_Parity : PageModel
    {
    public static JsonResult OnPost(TestValues myString)
        {
             var test = myString;
             return new JsonResult("");
        }
    }
}
var output = {
    test1: 'hallo',
    test2: 'peter',
    test3: 'how are you'
};
console.log(output);

$.ajax({
    type: "POST",
    url: "Conf_Parity",
    dataType: "json",
    data: JSON.stringify(output),
    contentType: "application/json; charset=utf-8",                                
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },                                                                
    failure: function (response) {
        alert(response);
    }
});
2
  • Change datatype to application/json Commented Jul 8, 2019 at 10:26
  • sadly isn't fixing it, but thanks for your input! Commented Jul 8, 2019 at 11:05

1 Answer 1

1

I wouldn't post JSON to a page handler generally. There is rarely a good reason for doing so. I would just post the form data as you have it prior to applying the JSON.stringify method to it. I would only post JSON to an API endpoint that required it.

But if you want to post JSON regardless, you need to access the JSON from the Request body and deserialise it:

public async Task OnPostAsync()
{

    using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
    {
        var body = await reader.ReadToEndAsync();
        var testValues = JsonConvert.DeserializeObject<TestValues>(body);
        // do something with testValues.test1 etc.
    }
}

Note - there are no parameters to the OnPostAsync handler. Model binding doesn't work with JSON.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.