2016-11-10 39 views
0

我有一個控制器操作,它執行SQL查詢並將模型類型的列表傳回給視圖。該視圖然後輸出一個簡單的表格,其中包含每個模型中包含的數據。如何處理出現在MVC模型中的空日期時間

我的模型:

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"] 
} 

回答

3

變化從DateTime爲可空的DateTime(DateTime?)的屬性類型。

public class UserModel 
{ 
    // Your existing properties goes here 

    public DateTime? LastUpdatedDate { get; set; } 
} 
在SQL

現在,不與任何日期時間值(如:1900-01-01)取代NULL。只需返回NULL

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

當您從數據閱讀器讀取數據時,請執行空檢查。如果該值不爲空,則將其分配給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")); 
} 
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; } 
相關問題