AJAX发布数据到达ASP.NET Core 2.1控制器时为空 [英] AJAX post data is null when it reaches the ASP.NET Core 2.1 controller
问题描述
我正在使用以下jQuery代码将数据发布到ASP.NET Core MVC 2.1.2页面:
I'm posting data to an ASP.NET Core MVC 2.1.2 page using this jQuery code:
function OnCountryChange() {
$.ajax({
url: "/OnCountryChange",
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
headers: {
"RequestVerificationToken": $('input[name = __RequestVerificationToken]').val()
},
data: JSON.stringify({
sCountryCode: "Test 123"
})
});
}
我通过这种方法在控制器中收到帖子:
I am receiving the post in the controller with this method:
[HttpPost]
[ValidateAntiForgeryToken]
[Route("/OnCountryChange")]
public IActionResult OnCountryChange([FromBody] string sCountryCode)
{
logger.LogDebug($"Country code is: {sCountryCode ?? "null"}");
return Json(sCountryCode);
}
输出到日志的输出是:
国家/地区代码为:空
Country code is: null
原始请求正文(使用Fiddler查看)如下:
The raw request body (viewed using Fiddler) looks like this:
{"sCountryCode":"Test 123"}
为什么不传递数据?
推荐答案
我对C#
不熟悉,但是在您的问题中您已经添加
I am not familiar with C#
,but in your question you have add
contentType: "application/json; charset=utf-8"
在Ajax
方法中
表示数据参数为json
格式,因此您需要作为json
对象而不是直接访问字符串进行访问.
in your Ajax
method which means the data parameter is json
format,so you need to access as json
object instead of access string directly.
两种解决方法:
a.更改您的C#
控制器方法以像json
对象一样访问
a. Change your C#
controller method to access like a json
object
b.发送不带json
的Ajax
参数,代码类似于以下代码:
b. Send Ajax
parameter without json
,code similar to below:
function OnCountryChange() {
$.ajax({
url: "/OnCountryChange",
type: "POST",
datatype: "json",
headers: {
"RequestVerificationToken": $('input[name = __RequestVerificationToken]').val()
},
data: {sCountryCode: "Test 123"}
});
}
这篇关于AJAX发布数据到达ASP.NET Core 2.1控制器时为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!