简体   繁体   中英

Handling DateTime DbNull in mvc label using ?? operator

I am trying to handle dbnull using the?? operator. I know I can test for dbnull using == equal operator. But I would like to shorten the code with?? operator. Here is what I have so far but not working:

@Html.Label(Model.CustomerDate.ToString() ?? "", new { id = "CustomerDate" })

But it is not working. Model.CustomerDate is a DateTime? type. I have searched and found no results specific to above scenario. Any help would be appreciated.

Update #1

I tried the following as suggested by Joel below:

@Html.Label(Model.CustomerDate.ToString(), new { id = "CustomerDate" })

This did not work since the field is a DateTime?. I receive the error "Object reference not set to an instance of an object." I have to handle null, dbnull and a valid datetime value.

Update #2

I was able to figure out a working solution thanks to Joel's answer below:

Note: You have to have a space in the double quotes after the?? section below, if not it will not render the control when null:

@Html.Label(Model.CustomerDate?.ToString() ?? " ", new { id = "CustomerDate" })

DBNull is not the same as a C# null , and does not work with the null-coalescing ?? operator like that. You have compare with DBNull.Value .

Aside from that, DBNull.ToString() will already produce an empty string, such that you should be able to simply remove the null-coalescing operation like this:

@Html.Label(Model.CustomerDate.ToString(), new { id = "CustomerDate" })

That will give you the empty string you want if you have null, or create a string from the DateTime value if you don't, using the format for the current culture of the process (usually the server default, but in an ASP.Net context you can sometimes set things to infer from the browser).

If you also need to handle a Nullable type, you can do this:

@Html.Label(Model.CustomerDate?.ToString() ?? "", new {id = "CustomerDate"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM