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