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
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 thetestNumber
argument.TestMethod(int testNumber)
action method is expecting parameterint testNumber
, therefore it’s necessary to use this name when referencing to the parameter in the JavaScript.contentType
definition. By default it will beapplication/x-www-form-urlencoded; charset=UTF-8
which is fine for most cases.