如何将 JSON 字符串从 AJAX 调用传递到 .Net Core 控制器操作?

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

我已经阅读了几个这样的例子,但就是无法让它工作。我试图将 json 数据传递给 .Net Core 控制器操作,并且该值在我的操作方法中始终为 null。我已经尝试了这里的多种变体,但似乎没有任何效果。在此示例中,我将位置设置为文字,以确保我尝试传递有效的 JSON。

Javascript:

function GetRatedPlaces(places) {
            places = { name: "John", age: 30, city: "New York" };
            var placesJson = JSON.stringify(places);
            console.log(placesJson);
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetRatedPlaces", "Home")',
                contentType: 'application/json',
                data: placesJson,
                cache: false,
                success: function (result) {
                    // Handle the response from the controller
                }
            });
        }

控制器动作:

 [HttpPost]
        public IActionResult GetRatedPlaces([FromBody] string places)
        {
            // Deserialize places here.

            return Ok();
        }
javascript .net ajax asp.net-mvc core
1个回答
0
投票

您可以尝试以下代码:

function GetRatedPlaces(places) {
            places = { name: "John", age: 30, city: "New York" };
            var placesJson = JSON.stringify(places);
            console.log(placesJson);
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetRatedPlaces", "Home")',
               
                data: places,
                
                success: function (result) {
                    // Handle the response from the controller
                }
            });
        }

该动作设置参数来绑定数据:

[HttpPost]
public IActionResult GetRatedPlaces( string name,int age,string city)
{
    // Deserialize places here.

    return Ok();
}

结果:

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