0

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(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 });
}

1 Answer 1

1

Previously, I was sending data as content type:

contentType: "application/json; charset=utf-8",

I changed it to:

contentType: "application/x-www-form-urlencoded; charset=utf-8",

Data is now being transferred successfully.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.