ajax POST int parameter in asp.net core ajax POST int parameter in asp.net core ajax ajax

ajax POST int parameter in asp.net core


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}


I believe your issue could be that you are passing an object to the api, but trying to turn it into a primitive. I know there is already a chosen answer, but give this a whirl.

var data = { };data["objId"] = 1; //I just wanted to show you how you can add values to a json object$.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);    }});

You create a model class

public class MyModel {     public int ObjId {get;set;}}

Your controller should expect one of these

[HttpPost]public JsonResult PassIntFromView([FromBody] MyModel data){    //DO stuff with int here}


Try this:

var data = { "objId": 1};$.ajax({    url: '@Url.Action("PassIntFromView", "ControllerName")',    data: data,    type: "POST",    dataType: 'JSON',    contentType: "application/json",    success: function(data) {        //do stuff with json result     },    error: function(passParams) {        console.log("Error is " + passParams);    }});

Your controller:

[HttpPost]public JsonResult PassIntFromView(int objId){    //DO stuff with int here}