skip to Main Content

I’m trying to send the value via JS code value via Post request, but I don’t get this value. I can’t figure out what the problem is.

JS Code:

$(document).ready(function () {
    $("#TestButton").click(function (e) {
        var valueToSend = 1; 
        $.ajax({
            url: "Home/TestMethod",
            type: "POST",
            dataType: 'json',
            data: valueToSend,
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                alert("Success");
            },
            error: function (xhr, status, error) {
                alert("Failed");
            },
        })
    })
})

Controller:

public class HomeController : Controller
{
    public async Task<IActionResult> Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult TestMethod(int testNumber)
    {
        var value = testNumber;
        return View(nameof(Index));
    }
}

HTML Code:

<div>
    <input type="submit" value="Test" class="btn btn-default" id="TestButton" />
</div>

I expect to get the number 1, but the number 0 comes.
The result of the post request

2

Answers


  1. You are sending 1 in the request body. However, it doesn’t seem like your endpoint expects a request body. It probably treats the testNumber argument as a query string parameter. Try calling your endpoint with query string parameter.

    Home/TestMethod?testNumber=1

    Another option is that you can try adding [FromBody] attribute to the testNumber argument.

    [HttpPost]
    public IActionResult TestMethod([FromBody] int testNumber)
    {
        var value = testNumber;
        return View(nameof(Index));
    }
    
    Login or Signup to reply.
    1. The TestMethod(int testNumber) action method is expecting parameter int testNumber, therefore it’s necessary to use this name when referencing to the parameter in the JavaScript.
    2. Remove the contentType definition. By default it will be application/x-www-form-urlencoded; charset=UTF-8 which is fine for most cases.
    $(document).ready(function () {
        $("#TestButton").click(function (e) {
            var valueToSend = 1; 
            $.ajax({
                url: "Home/TestMethod",
                type: "POST",
                dataType: 'json',
                data: { testNumber: valueToSend },
                //contentType: "application/json; charset=utf-8",
                success: function (response) {
                    alert("Success");
                },
                error: function (xhr, status, error) {
                    alert("Failed");
                },
            })
        })
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search