2013-04-05 86 views
0

我有一個關於在Asp.net MVC4日期驗證的問題。 我用數據註解日期驗證如下Modelstate總是拋出無效的日期時間錯誤

[DataType(DataType.Date)] 
    [AllowHtml] 
    [DisplayFormat(HtmlEncode = false, ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]  
    [Display(Name = "Date Of Birth")] 
    public Nullable<System.DateTime> DateOfBirth { get; set; } 

接下來,在HTML頁面時,我正在使用MVC HTML表單

@Html.TextBoxFor(model => model.UserSettings.DateOfBirth, 
          String.Format("{0:dd/MM/yyyy}", 
          model.UserSettings.DateOfBirth), 
         new { id = "DoB", @class = "brth-ipt" }) 

最後下面,我使用一個jQuery的日期選擇器如下

$(function() { 
    $("#DoB").datepicker("destroy"); 
    $("#DoB").datepicker({ 
     showOn: "both", 
     beforeShow: customRange, 
     dateFormat: "dd/mm/yy", //"mm-dd-yy", 
     firstDay: 1, 
     changeFirstDay: false, 
     changeMonth: true, 
     changeYear: true, 
     yearRange: "-150:+0" 
    }); 
}); 

我的問題是,當我選擇從日期選擇一個日期,它顯示爲毫米/ dd/yyyy格式並能正常工作。

但是當我再次加載頁面來編輯窗體時,它以mm-dd-yyyy格式顯示。現在,當我保存表單而沒有修改前一個日期(mm-dd-yyyy格式)時,我無法保存表單,因爲Data annotation vaidation正在向我發送一個錯誤。 「日期不是有效格式」。

我無法解決此問題。

回答

0

試試這個:

[DataType(DataType.Date)] 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")] 
    [Display(Name = "Date Of Birth:")] 
    public DateTime? DateOfBirth { get; set; } 

據我所知,你甚至不會需要使用Jquery Date picker。該框架內置了幫助程序來選擇日期。

在你看來

<div class="editor-label"> 
     @Html.LabelFor(model => model.DateOfBirth) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.DateOfBirth) 
     @Html.ValidationMessageFor(model => model.DateOfBirth) 
    </div> 

這在谷歌瀏覽器測試

0

Html.TextBoxFox()沒有考慮[DisplayFormat]考慮。要利用此屬性並實現您的目標,您可以使用

Html.EditorFor(x => x.UserSettings.DateOfBirth, new {id = "DoB", @class = "brth-ipt"})