Stivin
Stivin

Reputation: 197

Asp.Net Mvc POST method doesn't send string

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?

Upvotes: 2

Views: 2412

Answers (1)

Yodacheese
Yodacheese

Reputation: 5037

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

Upvotes: 3

Related Questions