.NET 6(VS2022)中jQuery Ajax向Controller传值为Null的问题
解决.NET 6中AJAX POST参数为Null的问题
问题分析
核心问题集中在三点:
- .NET 6默认模型绑定规则不会自动从JSON请求体中读取简单类型参数
- 前端手动拼接JSON字符串易因特殊字符导致格式错误
- 前端指定
dataType: "json"但控制器返回纯文本,会触发解析异常
修正方案(推荐强类型接收)
1. 创建参数接收模型类
添加一个简单的模型类用于接收AJAX参数:
public class NameRequest { public string Name { get; set; } }
2. 修改控制器方法
添加[FromBody]特性指定从请求体读取参数,并返回JSON格式响应:
[HttpPost] public IActionResult AjaxMethod([FromBody] NameRequest request) { string currentDateTime = $"Hello {request.Name}. Current DateTime: {DateTime.Now}"; return Json(currentDateTime); }
3. 修正前端JavaScript代码
使用JSON.stringify生成合法JSON字符串,避免手动拼接的格式风险:
$(function () { $("#btnGet").click(function () { $.ajax({ type: "POST", url: "/Home/AjaxMethod", data: JSON.stringify({ name: $("#txtName").val() }), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { $("#txtresponse").val(response); }, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); }); });
备选方案(直接接收字符串)
若无需创建模型类,可调整为直接接收字符串参数:
控制器代码
[HttpPost] public IActionResult AjaxMethod([FromBody] string name) { string currentDateTime = $"Hello {name}. Current DateTime: {DateTime.Now}"; return Json(currentDateTime); }
前端代码
发送纯字符串格式的JSON请求体:
$(function () { $("#btnGet").click(function () { $.ajax({ type: "POST", url: "/Home/AjaxMethod", data: JSON.stringify($("#txtName").val()), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { $("#txtresponse").val(response); }, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); }); });
内容的提问来源于stack exchange,提问作者cecy vargas
相关产品推荐
相关产品推荐

