I am trying to pass Data from a view to my Controller. I am getting the values in Ajax correctly but I am unable to pass them to the controller. I get the comment in controller as null always.
Ajax code from View:
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);
}
});
}
Controller Code:
[HttpPost("/PostCommentInput")]
public IActionResult PostCommentInputHandler([FromBody] string comment)
{
Console.WriteLine("Comment: " + comment);
return Json(new { status = comment });
}
I have seen few solutions here in stack overflow but nothing is working for me.
In my project, I am doing this at some point and its working there:
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
});
Controller:
[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 });
}