2014-02-20 40 views
1

我會問一個關於處理日期的非常基本的問題,但對我來說,處理它始終是一個問題。我的問題是,有時我們可以選擇顯示DatePicker。我大多使用jQueryUIKendoUI。這是正常情況,但結合我主要使用DateTime屬性與模型:有關更好地處理日期的邏輯

型號:

public DateTime? DateOfService { get; set; } 

鑑於:

@Html.TextBoxFor(m => m.DateOfService, new { @readonly = "readonly" }) 
<script> 
    $("#DateOfService").datepicker(); 
</script> 

假設在數據庫中,我有一個字段爲空,這是DateTime數據類型。 現在,用戶可以將該字段留空,以便在模型中使用可以爲null的類型屬性。假設用戶選擇日期並點擊保存。當用戶來編輯頁面時,datePicker也顯示「2/18/2014 12:00:00 AM」的時間。

如果我在模型中使用字符串時間的屬性,那麼它總是會在保存時轉換爲DateTime,然後在檢索時轉換爲字符串類型。而且,驗證也變得忙碌起來。

你能指導我什麼是我可以在MVC中使用的最好的方法來處理日期的網頁領域?

+0

KendoUI DatePicker可以格式化'DateTime'值。我總是使用[這些可用格式]格式化日期(http://docs.telerik.com/kendo-ui/getting-started/framework/globalization/dateformatting)。 –

+0

但是你特別喜歡劍道。請建議一些通用的。 – Sweetie

+1

它沒有任何區別。兩個控件都提供日期格式。對於Kendo看[這個鏈接](http://docs.telerik.com/kendo-ui/getting-started/framework/globalization/dateformatting)和JQueryUI請看[這一個](http://api.jqueryui.com /日期選擇器/#公用事業formatDate)。 –

回答

1

您是否嘗試過使用DescriptionAttribute

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] 
public DateTime? DateOfService { get; set; } 

這應該以適合的格式顯示日期。

+0

你能否也請告訴我,DatePicker模型中的DateTime屬性更好,或者我們可以使用字符串Type屬性。哪個更好? – Sweetie

+0

上述屬性不起作用lol – Sweetie

+0

@Sweetie該屬性需要與'EditorFor'調用一起使用。 – Kami