如何处理出现在MVC模型中的null datetime

时间:2016-11-10 17:13:57

标签: c# asp.net-mvc

我有一个控制器操作,它执行SQL查询并将模型类型列表传递回视图。然后视图输出一个简单的表,其中包含每个模型中包含的数据。

我的模特:

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

我的观点:

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

对于数据中的某些行,LastUsedDate和LastUpdated日期为空,因此它们采用1900-01-01,它们将在视图中显示。

如果它是1900-01-01,有没有办法显示这个值?

我在控制器中的查询是

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

我将它们分配给模型:

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

2 个答案:

答案 0 :(得分:3)

将属性类型从DateTime更改为可为空的DateTime(DateTime?)。

public class UserModel
{
    // Your existing properties goes here

    public DateTime? LastUpdatedDate { get; set; }
}

现在在SQL中,不要将NULL替换为任何日期时间值(例如:1900-01-01)。只需返回NULL

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

从数据读取器读取时,请执行空检查。如果该值不为null,则将其分配给LastUpdatedDate属性。

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

答案 1 :(得分:0)

将模型更改为使用Nullable<DateTime>

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