.net core MVC 使用 jquery ajax请求 Post json
JQuery发起Post请求 参数Json方式
$.ajax({
url: '@Url.Action("SEOGenerate")',
data: {
title:'test'
},
type: 'POST',
dataType: 'json',
//contentType: 'application/json; charset=utf-8', // 不能带上这句话,带上的话请求参数会编程键值对方式,不知道为什么
success: function (res) {
console.log('请求成功')
},
error: function (xhr) {
console.log('请求失败')
alert(xhr.responseText);
}
});
.net Core MVC后台action示例
[HttpPost]
public IActionResult SEOGenerate(SEOGenerateModel data)
{
return NoContent();
}
jquery使用post方式提交Array数组到MVC后台
前台js代码
C# 全选
$.ajax({
url: url,
type: 'post',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(ids),
success: function (res) {
if (res.status == 0) {
GZDialog.alert({
message: `转换成功`,
title: '保存成功',
btnok: "确定",
btnOkClass: "btn-success"
}).on(function (isOK) {
window.location.reload()
});
}
else
GZDialog.alert(res.message);
},
error: function (xhr, errorText, errorType) {
GZDialog.alert(xhr.responseText);
}
})
因为直接Array
数组,如果不设置ContentType
,会默认为 xx-form的方式提交,这样数据格式就错误了,后台收不到
所以这里一定要设置contentType
为 application/json; charset=utf-8
还需要设置data
为json字符串
,JSON.stringify(data)
,不然传值也是错误的
后台代码
C# 全选
// 转换组件为本地
[HttpPost]
public IActionResult ConvertToLocal([FromBody] List<string> ids)
{
try
{
entities.data_PageBuildComponents.Where(w => ids.Contains(w.RowID) && w.IsServerLink)
.BatchUpdate(p => new data_PageBuildComponents()
{
IsServerLink = false
}
);
//return APIBad("失败");
entities.SaveChanges();
return APISuccess("操作成功", null);
}
catch (Exception ex)
{
return APIBad(ex.Message);
}
}
因为前台设置了contentType
为json,后台如果不用FormBody
特性将接收不到数据
方法得 [HttpPost]
不能少,如果缺少,同样不能接收到数据
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 管理员