POST Json到剃须刀页面

I'm new to razor pages in .Net core and I have some trouble to understand how it works in case of AJAX Post.

I have created a sample project to explain my problem

I have one simple form with three input in a file called Index.cshtml:

<form method="post">
    firstname :
    <input id="firstname" type="text" name="firstname" />
    name:
    <input id="name" type="text" name="name" />
    message:
    <input id="message" type="text" name="message" />

    <input type="submit" value="Submit">
</form>

<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
    $(document).ready(function(){
        $("form").submit(function () {
            var message = {
                firstname: $("#firstname").val(),
                name: $("#name").val(),
                message: $("#message").val()
            }

            $.ajax({
                url: "/Index",
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(message),
                success: function () {
                    console.log("success")
                },
 
            });
        })
    });
</script>

I want to send my json object (message) to my OnPost() function in PageModel :

    public class IndexModel : PageModel
    {
        public void OnGet()
        {

        }

        public void OnPost(string json)
        {
            Console.WriteLine(json);
        }
    }

Problem is that it's null,

I have also try :

data: { "json" : JSON.stringify(message) },

But in my OnPost method, json is always null.

Can you explain me where is my mistake ?

Thank you

</div>

This is an issue about Model Binding .When you post the data as Json ,the data received is a json object like {"firstName":"Andrew","name":"Lock","message":"Hello"}.

So you should use a model Message as the parameter in the handler ,in order to bind the JSON correctly in ASP.NET Core, you must modify your action to include the attribute [FromBody] on the parameter.

You could take a look at the Model binding JSON POSTs in ASP.NET Core.