Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax POST int parameter in asp.net core

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.

like image 330
domshyra Avatar asked Mar 07 '19 23:03

domshyra


People also ask

Can AJAX use post?

post() makes Ajax requests using the HTTP POST method. The basic syntax of these methods can be given with: $. get(URL, data, success); —Or— $.

What is data type in AJAX jquery?

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.

What is FromBody ASP NET core?

[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.

What is AJAX in Javascript with example?

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.


1 Answers

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
}
like image 56
Xueli Chen Avatar answered Sep 21 '22 14:09

Xueli Chen