0

I don't know what I'm missing.

Everything works when passing complex custom objects, but when I try to pass a simple int or string I get null

Here is the ajax call on client side:

var id = 1;
$.ajax({
   type: "GET",
   url: "/api/APICalls/MethodName",
   contentType: "application/json; charset=utf-8",
   data: JSON.stringify(id), // or JSON.stringify({id: id}) or just id
   dataType: "json",
   success: function (data) {
       console.log(data);
   },
   error: function (data) {
       alert(data.responseText);
   }
});

On server side the method is as follows:

[HttpGet]
public void MethodName([FromBody] string id)
{
    // Do something with id... Doesn't matter... It is `null`!
}
norbitrial
  • 14,716
  • 7
  • 32
  • 59
Oiproks
  • 764
  • 1
  • 9
  • 34

1 Answers1

2

The reason why you are getting null value for id parameter is [FromBody]. Technically when you send GET request to the server with jQuery the data is presented in the query parameters and not in the request body.

What you need to do on backend side is just to remove [FromBody] as follows:

[HttpGet]
public void MethodName(string id)
{
    // Now you should be able to access the value of id
}

Sending data from client side as the following:

var id = 1;

$.ajax({
   url: '/api/APICalls/MethodName',
   type: 'GET',
   data: {id: id},
   success: function (data) {
      console.log(data);
   },
   error: function (err) {
      console.error(err);
   }
});

From the documentation for [FormBody] you can read the following:

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.

Your data was presented in the query string, checking the network tab in Chrome:

enter image description here

enter image description here

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
  • That helped a lot. Thanks. Just one more clarification. I should define the `dataType` and `contentType` only on `post` calls? What if I want to use an object as parameter for `GET`. Something like `object = {param1: 1, param2: 2}`. Then it will be `data: {paramObject: object}` and on server side `MethodName(ObjectType paramObject)`. Is that correct? – Oiproks Nov 24 '19 at 16:45
  • 1
    I would send the data with `POST` request in that case and define the types. If you are interested further please find this answer, this explains more about complex objects: https://stackoverflow.com/questions/24874490/pass-multiple-complex-objects-to-a-post-put-web-api-method/24876680#24876680 – norbitrial Nov 24 '19 at 16:53