3
votes

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

1
you could add the model on the controller side?karritos
I added a Model "Message" and change the parameter of the function OnPost like this : public void OnPost(Message json), in this case it's working but I don't know why it's not working with a raw JSON. If I removed the name attribute of the input field with the same JSON, it's not working anymore, how it works ?Alex_K
@Alex_K does OnPost(string json) work if you just pass in the string "test" instead of your JSON? That ought to help you figure out whether the problem is with passing in a JSON model or with the way you're calling the controller.Matt Shepherd
If I send a simple string "test" to controller, json parameter of my controller is null. I can post information from form (binded with name attribute) but If i send information from "data" of AJAX request, it's not working.Alex_K

1 Answers

2
votes

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.