I am migrating my MVC project to Core and I have been having a hard time fixing all the old ajax calls.
I can pass a model and string parameters into the controller, however, ints are not working for me.
I can wrap them into a JSON object as a string parameter such as [FromBody]string objId
in the controller, but then I have to parse the int val from the Json {'objId' : 1}
.
Is there a way I can avoid this and just pass an int?
below is the code I am trying.
[HttpPost]
public JsonResult PassIntFromView([FromBody]int objId)
{
//DO stuff with int here
}
here is the js.
var data = { "objId": 1};
$.ajax({
url: '@Url.Action("PassIntFromView", "ControllerName")',
data: JSON.stringify(data),
type: "POST",
dataType: 'JSON',
contentType: "application/json",
success: function(data) {
//do stuff with json result
},
error: function(passParams) {
console.log("Error is " + passParams);
}
});
The objId
is always 0 in the controller.
I have tried this without doing JSON.stringify(data)
as well with no result.
I have also tried all the different form attribute variations.
post() makes Ajax requests using the HTTP POST method. The basic syntax of these methods can be given with: $. get(URL, data, success); —Or— $.
The available data types are text , html , xml , json , jsonp , and script . If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.
[FromBody] attributeThe ASP.NET Core runtime delegates the responsibility of reading the body to an input formatter. Input formatters are explained later in this article.
AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Try to use contentType as 'application/x-www-form-urlencoded'
:
var data = { objId: 1 };
$.ajax({
url: '@Url.Action("PassIntFromView", "ControllerName")',
type: "post",
contentType: 'application/x-www-form-urlencoded',
data: data,
success: function (result) {
console.log(result);
}
});
Then remove the [FromBody]
attribute in the controller
[HttpPost]
public JsonResult PassIntFromView(int objId)
{
//Do stuff with int here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With