我正在尝试将数据从视图传递到我的控制器。我在 Ajax 中正确获取了值,但无法将它们传递给控制器。我在控制器中得到的注释总是为空。
查看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 });
}
我在堆栈溢出中看到了一些解决方案,但没有任何解决方案对我有用。
在我的项目中,我在某个时候这样做并且它在那里工作:
const likeClickHandler = (PostID) => {
$.ajax({
type: "POST",
url: "/Like/",
ontentType: "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",
我把它改为:
contentType: "application/x-www-form-urlencoded; charset=utf-8",
数据现已成功传输。