Heitor Giacomini
Heitor Giacomini

Reputation: 474

How to pass empty string to nullable int

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]

Upvotes: 2

Views: 2040

Answers (3)

Mykyta Halchenko
Mykyta Halchenko

Reputation: 798

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);

Upvotes: 1

Heitor Giacomini
Heitor Giacomini

Reputation: 474

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;
};

Upvotes: 0

Vali.Pay
Vali.Pay

Reputation: 384

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

Upvotes: 1

Related Questions