aspnet 控制器中的 ajax POST 始终值为 null

问题描述 投票:0回答:1

在我的 asp net core 8 项目中,我有一个 ajax 帖子,但是 参数值始终返回 null

我已经写了 builder.Services.AddControllers().AddNewtonsoftJson();在我的 Program.cs 文件中

这是我的控制器代码

using Microsoft.AspNetCore.Mvc;

namespace MyProject.Controllers
{
    [Route("Test")]
    public class TestController : Controller
    {

        [HttpGet]
        [Route("index")]
        public IActionResult Index()
        {
            return View();
        }


        [HttpPost]
        [Route("callPost")]
        public IActionResult CallPost(ParamClass model)
        {


            return View();
        }
    }

    public class ParamClass()
    {
        public string P1 { get; set; }
        public string P2 { get; set; }
    }
} 

这是我的ajax post调用

 $(document).ready(function () {


            var model = {
                p1: "a",
                p2: 'b'
            };

            $.post({
                url: "/test/callPost",
                data: JSON.stringify({ model }),
                dataType: "json",
                contentType: "application/json",
                success: function (data) { 
            });

        });
 

enter image description here

asp.net-core
1个回答
0
投票

答案

你实际上并不需要

JSON.stringify
- 只需使用你的 JavaScript 模型:

$.post({
    url: "/test/callPost",
    data: model,
    dataType: "json",
    contentType: "application/json",
    success: function (data) { 
});

$.post
将为您处理对象的序列化。如果您真的想使用 JSON.stringify,请省略大括号:

$.post({
    url: "/test/callPost",
    data: JSON.stringify(model),
    dataType: "json",
    contentType: "application/json",
    success: function (data) { 
});

为什么

当你调用这行代码时:

JSON.stringify({ model })

您首先使用模型作为属性创建一个新对象。

{
    "model": {
        p1: "a",
        p2: 'b'
    }
}

然后,该新模型被序列化为:

"{\"model\":{\"p1\":\"a\",\"p2\":\"b\"}}"

这与您的

CallPost()
操作模型不匹配。将模型直接传递给 JSON.stringify,

JSON.stringify(model)

会回来

"{\"p1\":\"a\",\"p2\":\"b\"}"

哪个正确绑定到您的 C# 模型。

© www.soinside.com 2019 - 2024. All rights reserved.