2

Ajax doesn't send any strings to the controller.

Here's my function:

$(function () {
    $('#btnAnswer').click(function () {
        var code = $('#Answer').val();
        $.ajax({
            url: '@Url.Action("CheckAnswer", "Home")',
            type: "POST",
            data: code ,
            datatype: "text",

            success: function (resultFromFunct) {
                $("#resultsBox").append(resultFromFunct);
            }

        });
        $('#Answer').val('');
    });
});

Here's my controller:

[HttpPost]
public string CheckAnswer(string answer)/
{
    game.LogUserAnswer(Request.Cookies["user"].Value, answer);           
    return String.Format("<strong>{0}</strong>: {1} <br>", Request.Cookies["user"].Value, game.UserGuess(answer));
}

Ajax is correctly get into CheckAnswer method but answer is always null. I've tried other examples from stack, for instance Asp.Net Mvc JQuery ajax input parameters are null but always get null result. Do you have any thoughts of the cause?

3
  • 4
    Change data: code , to data: { answer: code }, Commented Nov 10, 2015 at 20:59
  • Thanks, Stephen. Such a dumb mistake. Don't know how to vote for your comment. Commented Nov 10, 2015 at 21:06
  • 1
    Yodacheese has added an answer so you can accept that :) Commented Nov 10, 2015 at 21:18

1 Answer 1

3

Change your request parameters to data: { answer: code } in your request. It probably can not match code to the parameter on your action.

$(function () {
    $('#btnAnswer').click(function () {
        var code = $('#Answer').val();
        $.ajax({
            url: '@Url.Action("CheckAnswer", "Home")',
            type: "POST",
            data: { answer: code },
            datatype: "text",

            success: function (resultFromFunct) {
                $("#resultsBox").append(resultFromFunct);
            }

        });
        $('#Answer').val('');
    });
});
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.