weixin_33736649 2019-01-28 19:02 采纳率: 0%
浏览 36

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" />
    <input id="name" type="text" name="name" />
    <input id="message" type="text" name="message" />

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

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

                url: "/Index",
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(message),
                success: function () {

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)

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条回答 默认 最新

  • weixin_33721427 2019-01-29 10:13

    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.




    • ¥80 关于海信电视聚好看安装应用的问题
    • ¥15 vue引入sdk后的回调问题
    • ¥15 求一个智能家居控制的代码
    • ¥15 ad软件 pcb布线pcb规则约束编辑器where the object matpcb布线pcb规则约束编辑器where the object matchs怎么没有+15v只有no net
    • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
    • ¥20 求各位能用我能理解的话回答超级简单的一些问题
    • ¥15 yolov5双目识别输出坐标代码报错
    • ¥15 这个代码有什么语法错误
    • ¥15 给予STM32按键中断与串口通信
    • ¥15 使用QT实现can通信