Home > Mobile >  How to pass empty string to nullable int
How to pass empty string to nullable int

Time:04-19

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]

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related