POST Json到剃须刀页面 [英] POST Json to from razor pages
问题描述
.Net核心中的剃刀页面是我的新手,在了解AJAX Post情况下的工作原理时遇到了一些麻烦.
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
我有一个简单的表单,在名为Index.cshtml的文件中有三个输入:
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>
我想将json对象(消息)发送到PageModel中的OnPost()函数:
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);
}
}
问题在于它为空,
我也尝试过:
data: {
"json" : JSON.stringify(message)
},
data: {
"json" : JSON.stringify(message)
},
但是在我的OnPost方法中,json始终为null.
But in my OnPost method, json is always null.
你能解释一下我的错误在哪里吗?
Can you explain me where is my mistake ?
谢谢
推荐答案
这是有关模型绑定的问题.当您将数据发布为Json时,接收到的数据是一个{"firstName":"Andrew","name":"Lock","message":"Hello"}
之类的json对象.
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"}
.
因此,您应该在处理程序中使用模型消息作为参数,以便在ASP.NET Core中正确绑定JSON,必须修改操作以在参数上包含属性[FromBody].
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.
您可以查看模型绑定JSON ASP.NET Core中的POST .
这篇关于POST Json到剃须刀页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!