2

I have this property

public int? CodigoBanco { get; set; }

An when i try to send it to server in this way

codigoBanco: ""

I have the following error

The following errors were detected during validation:\r\n - The JSON value could not be converted to System.Nullable`1[System.Int32]

Heitor Giacomini
  • 384
  • 2
  • 12
  • 3
    You can't do that. `int?` is not equal to `string`, you might use string for `CodigoBanco` – D-Shih Apr 19 '22 at 13:08
  • 6
    Or leave the property codigoBanco out of the json or set it to null (`codigoBanco: null`) – Ralf Apr 19 '22 at 13:15
  • @D-Shih can i set some convention so the server can handle it and auto convert empty string to null? – Heitor Giacomini Apr 19 '22 at 13:21
  • 1
    https://stackoverflow.com/questions/52177006/how-to-assign-int-variable-to-empty-in-c – Maytham Fahmi Apr 19 '22 at 13:36
  • 1
    you need a custom json converter, see [this qa](https://stackoverflow.com/a/57334833). `codigoBanco: ""` is not a valid integer. if you want to pass a null integer properly, you should just skip the property altogether (do not mention it in the json). – Bagus Tesa Apr 19 '22 at 13:44
  • @Maytham Since the dafault value for input is an empty string the property is send as codigoBanco: "" . Ralf suggestion worked very well to me. – Heitor Giacomini Apr 19 '22 at 13:59

3 Answers3

1

I don't know what's your point of doing that but simple way just casting:

CodigoBanco  =Convert.ToInt32(codigoBanco==""?null:codigoBanco)

the convert returns 0 into your int? property

Vali.Pay
  • 364
  • 1
  • 4
  • 16
1

You have two ways to resolve the problem:

  1. Specify null (not empty string) and it will be successfully mapped. codigoBanco: null or remove this property at all from client-side(the default will be the same null)

  2. Write custom convertaion at backend-side, something like:

    CodigoBanco = int.Parse(codigoBanco == "" || codigoBanco.Length = 0 ? null : codigoBanco);

Mykyta Halchenko
  • 720
  • 1
  • 3
  • 21
0

As @Ralf suggested, I removed all properties with empty string from json. This solved my problem:

function removeEmptyOrNull(obj){
    Object.keys(obj).forEach(k =>
        (obj[k] && typeof obj[k] === 'object') && removeEmptyOrNull(obj[k]) ||
        (!obj[k] && obj[k] !== undefined) && delete obj[k]
    );
    return obj;
};
Heitor Giacomini
  • 384
  • 2
  • 12