ASP.NET Core MVC中Ajax无法向控制器传递数据问题求助
问题描述
在ASP.NET Core MVC中尝试通过Ajax向控制器传递评论数据时,Ajax能正确获取到评论内容,但控制器的comment参数始终为null。
视图中的Ajax代码:
function handleCommentSubmitClick(PostID) { console.log("PostID: ", PostID); const comment = $("textarea[name='post-comment']").val(); $.ajax({ type: "POST", url: "/PostCommentInput", contentType: "application/json; charset=utf-8", dataType: "json", data: { comment: comment }, success: function (data, status) { console.log(data); }, error: function (xhr, status, error) { console.error("AJAX error: " + status + ' ' + error); } }); }
控制器代码:
[HttpPost("/PostCommentInput")] public IActionResult PostCommentInputHandler(string comment) { Console.WriteLine("Comment: " + comment); return Json(new { status = comment }); }
项目中类似的点赞功能可正常运行,代码如下:
视图Ajax代码:
const likeClickHandler = (PostID) => { $.ajax({ type: "POST", url: "/Like/", contentType: "application/json; charset=utf-8", dataType: "json", data: { PostID: PostID }, success: function (data, status) { successFunc(data, status); }, error: errorFunc }); }
控制器代码:
[HttpPost("/Like")] public IActionResult LikeHandler(long PostID) { string userId = User.FindFirstValue(ClaimTypes.NameIdentifier); UserPostRepository repo = new UserPostRepository(); List<int> Counts = repo.PostLike(PostID, userId); return Json(new { postIDController = PostID, Counts = Counts }); }
问题原因
你设置了contentType: "application/json; charset=utf-8",但传递的data是普通JavaScript对象,jQuery默认不会将其序列化为JSON字符串,而是会转换成表单编码格式(application/x-www-form-urlencoded)发送。后端ASP.NET Core MVC接收到的内容类型与声明的不一致,导致模型绑定无法正确解析comment参数。
点赞功能看似正常,是因为PostID是数值类型,模型绑定在处理表单编码数据时能自动匹配参数,但字符串类型的comment对格式要求更严格,所以出现了接收不到值的情况。
解决方案
提供两种可行的修改方案:
方案一:使用JSON格式传递数据
- 修改Ajax的
data部分,用JSON.stringify()将对象转为JSON字符串:
function handleCommentSubmitClick(PostID) { console.log("PostID: ", PostID); const comment = $("textarea[name='post-comment']").val(); $.ajax({ type: "POST", url: "/PostCommentInput", contentType: "application/json; charset=utf-8", dataType: "json", data: JSON.stringify({ comment: comment }), // 转为JSON字符串 success: function (data, status) { console.log(data); }, error: function (xhr, status, error) { console.error("AJAX error: " + status + ' ' + error); } }); }
- 控制器中创建一个模型类来接收参数,并添加
[FromBody]特性:
// 新增模型类 public class CommentRequest { public string Comment { get; set; } } [HttpPost("/PostCommentInput")] public IActionResult PostCommentInputHandler([FromBody] CommentRequest request) { Console.WriteLine("Comment: " + request.Comment); return Json(new { status = request.Comment }); }
方案二:使用表单编码格式传递数据
- 移除Ajax中的
contentType设置,让jQuery默认使用表单编码:
function handleCommentSubmitClick(PostID) { console.log("PostID: ", PostID); const comment = $("textarea[name='post-comment']").val(); $.ajax({ type: "POST", url: "/PostCommentInput", dataType: "json", data: { comment: comment }, success: function (data, status) { console.log(data); }, error: function (xhr, status, error) { console.error("AJAX error: " + status + ' ' + error); } }); }
- 控制器参数添加
[FromForm]特性,明确指定从表单数据中绑定:
[HttpPost("/PostCommentInput")] public IActionResult PostCommentInputHandler([FromForm] string comment) { Console.WriteLine("Comment: " + comment); return Json(new { status = comment }); }
内容的提问来源于stack exchange,提问作者M.Jafar
相关产品推荐
相关产品推荐

