我从javasript通过$ .ajax()函数向我的http控制器功能发送的json字符串为null

问题描述 投票:0回答:1
    SendData: function () {
            var jasonStr = JSON.stringify(GamePlayedObj);
            console.log(jasonStr);
            $.ajax({
                type: "POST",
                async: false,
                url: '@Url.Action("GamesSoFar", "AllCards")',
                dataType: "json",
                data: jasonStr,
                contentType: "application/json; charset=utf-8"
            });
        }

    [Route("Output")]
    [HttpPost]
    public ActionResult GamesSoFar(string jasonStr) {
        string j = jasonStr;
        string a = "";
        GameInfo InfoOfTheLastGame = JsonConvert.DeserializeObject<GameInfo>(jasonStr);
        _context.Add(InfoOfTheLastGame);
        _context.SaveChanges();
        var AllGames = _context.AllGames.Include(g => g.AllGames).ToList();
        return View(AllGames);
    }

我正在使用Asp.net核心webApi。我在函数控制器上使用的参数为null而不是json字符串。.j和a变量是出于调试原因,因此有任何想法吗?

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

您的代码将jasonStr放入请求主体,因此无法在控制器中获取数据。如果要获取jasonStr,则可以使用[FromBody]指定应使用请求主体绑定参数或属性并使用GameInfo jasonStr而不是string jasonStr绑定数据。

这里是一个演示作品:

GameInfo:

public class GameInfo
{
    public string name { get; set; }
    public int price { get; set; }
}

查看:

<div>
    <button onclick="SendData()">SendData</button>
</div>
@section scripts{
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript">
        var GamePlayedObj = {};
        GamePlayedObj.name = "game1";
        GamePlayedObj.price = 10;
        function SendData() {
            var jasonStr = JSON.stringify(GamePlayedObj);
            console.log(jasonStr);
            $.ajax({
                type: "POST",
                async: false,
                url: '@Url.Action("GamesSoFar", "AllCards")',
                dataType: "json",
                data: jasonStr,
                contentType: "application/json; charset=utf-8"
            });
        }


    </script>
}

控制器:

 [Route("Output")]
        [HttpPost]
        public ActionResult GamesSoFar([FromBody]GameInfo jasonStr)
        {
            string a = "";
            return View("OutPut");
        }

结果:

enter image description here

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