Razor Pages中AJAX POST数据无法被页面处理器正确解析
问题解决
你遇到的空集合问题主要是两个关键配置遗漏:
1. AJAX请求未指定正确的Content-Type
jQuery的AJAX默认contentType是application/x-www-form-urlencoded,但你提交的是JSON字符串,服务器无法正确解析这个格式的数据。需要显式设置contentType: "application/json":
修改后的AJAX代码:
$.ajax({ type: 'POST', url: '?handler=CheckNegativeWeights', data: JSON.stringify(sources), contentType: "application/json", // 必须添加这一行 headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() }, }) .done(function (response) { // ... }) .fail(function (response) { // ... })
2. 后端处理器参数未添加[FromBody]特性
Razor Pages的模型绑定默认不会从请求体中读取集合类型的数据,必须给参数加上[FromBody]特性,告诉框架从请求体解析JSON:
假设你的PageModel代码如下,修改处理器方法:
// 先定义对应的模型类 public class SourceItem { public bool IsStorage { get; set; } public string Source { get; set; } public int Volume { get; set; } public bool MarkAsEmpty { get; set; } } // 处理器方法 public IActionResult OnPostCheckNegativeWeights([FromBody] List<SourceItem> sources) { // 现在sources就能正确接收到前端提交的数据了 // ... 你的业务逻辑 }
额外注意
前端对象的键名(比如isStorage)和后端模型的属性名(IsStorage)不需要完全一致,因为JSON序列化默认支持驼峰命名匹配,框架会自动映射。
内容的提问来源于stack exchange,提问作者Jonathan Wood
相关产品推荐
相关产品推荐

