Empty string if null

后端 未结 4 1384
南方客
南方客 2020-12-08 14:09

I have this in my code:

SelectList(blah, \"blah\", \"blah\", cu.Customer.CustomerID.ToString())

It gives a error when it returns null, how

4条回答
  •  执笔经年
    2020-12-08 15:00

    It depends of the type of CustomerID.

    If CustomerID is a string then you can use the null coalescing operator:

    SelectList(blah, "blah", "blah", cu.Customer.CustomerID ?? string.Empty)
    

    If CustomerID is a Nullable, then you can use:

    SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())
    

    This will work because the ToString() method of Nullable returns an empty string if the instance is null (technically if the HasValue property is false).

提交回复
热议问题