Search code examples
jqueryajaxasp.net-core-mvcasp.net-ajax

Can't get data in controller from Ajax in ASP.NET Core MVC


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

Solution

  • 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.