2013-10-31 43 views
3

如果我在MVC中使用EditFor,我的日期時間字段顯示不是格式化的日期時間,如果我使用舊的學校html,我的字段不會收到錯誤類。MVC輸入日期時間

<div class="editor-field"> 
    <input type="text" name="EstimateTime" id="EstimateTime" value="<%: (Model != null) ? Model.EstimateTime.ToString("dd/MM/yyyy hh:mm:ss tt") : "" %>" /> 
    <%: Html.TextBoxFor(model => model.EstimateTime, new { @value = (Model != null) ? Model.EstimateTime.ToString("dd/MM/yyyy hh:mm:ss tt") : "" })%> 
    <%: Html.ValidationMessageFor(model => model.EstimateTime) %> 
</div> 

結果HTML:看的價值之間的差額:

<div class="editor-field"> 
    <input type="text" name="EstimateTime" id="EstimateTime" value="31/10/2013 01:54:42 PM" class="hasDatepicker"> 
    <input id="EstimateTime" name="EstimateTime" type="text" value="10/31/2013 1:54:42 PM" class="input-validation-error text-box single-line"> 
    <span class="field-validation-error">Isn't a date/time valid</span> 
</div> 

什麼是解決它的最佳實踐?

+0

它交換了一個月的一天。有什麼大不了的? –

+0

問題是,如果我使用Model.EstimateTime.ToString(「dd/MM/yyyy hh:mm:ss tt」)日期顯示爲格式MM/dd/..... – AFetter

回答

4
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] 
[DataType(DataType.Date)] 
public System.DateTime EstimateTime { get; set; } 

這是在Chrome

的最新版本爲我工作
+1

我不認爲鉻與它有任何關係。 – AFetter

2

DataFormatString添加到模型中的屬性。

public class YourModel 
{ 
    [DisplayName("Estimate Time:"), 
    DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss tt}")] 
    public System.DateTime EstimateTime { get; set; } 
    ... 
} 
+2

您還應該指定'ApplyFormatInEditMode ='DisplayFormat'屬性中的'true'。 – GWB

0

我總是用一個編輯模板,以完美的輸出控制

這是DateTime.cshtml:

@model System.DateTime? 

@{ 
    IDictionary<string, object> Attributes = new Dictionary<string, object>(); 
    if (ViewData.ContainsKey("style")) { 
     Attributes.Add("style", (string)ViewData["style"]); 
    } 
    if (ViewData.ContainsKey("autohelp")) { 
     Attributes.Add("title", (string)ViewData["autohelp"]); 
    } 
    if (ViewData.ContainsKey("autofocus")) { 
     Attributes.Add("autofocus", (string)ViewData["autofocus"]); 
    } 
    Attributes.Add("class", "fecha"); 
    Attributes.Add("autocomplete", "off"); 
} 


@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), Attributes)