.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

还需要设置datajson字符串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开发框架网发布内容,转载请附上原文出处连接
管理员
上一篇:html 两个image中间有间隙,有空隙,有空白,有间隔
下一篇:Javascript对URL进行编码解码的三种方式介绍
评论列表

发表评论

评论内容
昵称:
关联文章

.net core MVC 使用 jquery ajax请求 Post json
Jquery请求API,AJax,Post,Get提交,失败,错误的处理
使用.NET 6开发TodoList应用(6)——使用MediatR实现POST请求
.NET Core MVC中间件使用记录日志
【HttpHelper】HTTP Get和Post请求
C# HTTP或HTTPS Get请求Post 请求
.NET中大型项目开发必备(9)--http请求调用(Post与Get)
vue项目使用axios发送请求ajax请求头部携带cookie
yesweb-ajax使用
ASP.NET Core MVC中的路由约束
ASP.NET Core 中读取Post Request.Body 的正确姿势
asp.net - 在 ASP.NET Core MVC 中嵌套 TagHelper
ASP.NET MVC和ASP.NET Core MVC中获取当前URL/Controller/Action
javascript表单Form转json进行ajax提交Jquery表单json提交
使用.NET 6开发TodoList应用(10)——实现DELETE请求以及HTTP请求幂等性
C# ASP.NET Core开发学生信息管理系统(三)
.NETCore和.NET5 MVC解析获取appsettings.json数据
使用.NET 6开发TodoList应用(9)——实现PUT请求
asp.net core mvc修改cshtml试图热加载动态更新
.NET Core MVC 实现长时间任务的进度显示

联系我们
联系电话:15090125178(微信同号)
电子邮箱:garson_zhang@163.com
站长微信二维码
微信二维码