andrewb andrewb - 26 days ago 6
C# Question

How to handle null datetime appearing in MVC model

I have a controller action which performs a SQL query and passes a list of a model type back to the view. The view then outputs a simple table with the data contained in each model.

My model:

public class UserModel
{
[Key]
public string UserID { get; set; }
public string EmailAddress { get; set; }
public string Password { get; set; }
public string SecurityToken { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime CreatedDate { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime LastUsedDate { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime LastUpdatedDate { get; set; }
}


My view:

@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
@Html.DisplayFor(modelItem => item.SecurityToken)
</td>
<td>
@Html.DisplayFor(modelItem => item.CreatedDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastUsedDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastUpdatedDate)
</td>
</tr>
}


For some rows in the data, LastUsedDate and LastUpdated date are null, so they resort to 1900-01-01, and they are displayed in the view as such.

Is there a way to not show this value if it is 1900-01-01?

My query in the controller is

SELECT UserID, EmailAddress, SecurityToken, CreatedDate,
ISNULL(LastUsedDate, '1900-01-01') AS LastUsedDate,
ISNULL(LastUpdatedDate, '1900-01-01') AS LastUpdatedDate
FROM table1 ORDER BY CreatedDate DESC


And I assign them to the model like so:

var user = new UserModel
{
CreatedDate = (DateTime)reader["CreatedDate"],
LastUsedDate = (DateTime)reader["LastUsedDate"],
LastUpdatedDate = (DateTime)reader["LastUpdatedDate"]
}

Answer

Change the property type from DateTime to a nullable DateTime(DateTime?).

public class UserModel
{
    // Your existing properties goes here

    public DateTime? LastUpdatedDate { get; set; }
}

Now in your SQL, do not replace NULL with any date time value(ex : 1900-01-01). Just return NULL.

SELECT UserID, EmailAddress, SecurityToken, CreatedDate,LastUpdatedDate
FROM table1 
ORDER BY CreatedDate DESC

When you read from the data reader, do a null check. If the value is not null, then assign it to the LastUpdatedDate property.

var user = new UserModel
{
    EmailAddress = reader.GetString(reader.GetOrdinal("EmailAddress")),
    CreatedDate = reader.GetDateTime(reader.GetOrdinal("CreatedDate"))   
}
if(!reader.IsDBNull(reader.GetOrdinal("LastUpdatedDate")))
{
  user.LastUpdatedDate = reader.GetDateTime(reader.GetOrdinal("LastUpdatedDate"));
}