2017-05-06 88 views
8

我試圖處理用戶輸入的日期值,我要提示用戶輸入日期格式爲:DD/MM/YYYY指定MVC5(DD/MM/YYYY)日期格式

什麼我試圖做的:

我讀貫徹答案達林這樣一個問題: Format datetime in asp.net mvc 4

這是我實現:

在Global.asax中

在示範
(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var displayFormat = bindingContext.ModelMetadata.DisplayFormatString; 
     var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 

     if (!string.IsNullOrEmpty(displayFormat) && value != null) 
     { 
      DateTime date; 
      displayFormat = displayFormat.Replace 
      ("{0:", string.Empty).Replace("}", string.Empty); 
      if (DateTime.TryParse(value.AttemptedValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) 
      { 
       return date; 
      } 
      else 
      { 
       bindingContext.ModelState.AddModelError(
        bindingContext.ModelName, 
        string.Format("{0} is an invalid date format", value.AttemptedValue) 
       ); 
      } 
     } 

     return base.BindModel(controllerContext, bindingContext); 
    } 

出發日期:

[Required(ErrorMessage = "Departure date is required")] 
     [Display(Name = "Departure Date")] 
     [DataType(DataType.Date)] 
     [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] 
     public DateTime DepartureDate { get; set; } 

鑑於:

<div class="col span-1-of-2"> 
          @Html.LabelFor(m => m.DesignVacation.DepartureDate) 
          @Html.EditorFor(m => m.DesignVacation.DepartureDate) 

         </div> 

這是運行視圖時輸出: enter image description here

它始於本月(毫米)但我想要的是這種格式: dd/MM/yyyy

如何使用editorFor獲取此格式(如果可能則使用textboxFor)。

回答

3

如果你看看DisplayFormatAttribute.DataFormatString Property文件,你會看到

獲取或設置字段值的顯示格式。

沒有提到它會改變datepicker的設計格式,它只改變值的格式。因爲你是從HTML 5 date picker越來越日期你不能改變它的格式Is there any way to change input type=「date」 format? ,也有一些瀏覽器不支持HTML 5 date picker但你可以使用jquery date picker

head

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> 
<script src="https://code.jquery.com/jquery-1.12.4.js"></script> 
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 

添加這和body

@Html.TextBoxFor(m => m.DesignVacation.DepartureDate) 

,最後加上script

<script> 

    $(function(){ 

     $('#DesignVacation_DepartureDate').datepicker({ 
     dateFormat: 'dd/mm/yy' 
    }); 

}); 

</script> 
6

您正在使用EditorFor()並結合[DataType][DisplayFormat]屬性生成瀏覽器的HTML5日期選擇器。規格要求格式爲yyyy-MM-dd(ISO格式)。屬性更改爲:

[Required(ErrorMessage = "Departure date is required")] 
[Display(Name = "Departure Date")] 
[DataType(DataType.Date)] 
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] 
public DateTime DepartureDate { get; set; } 

和日期將顯示在用戶的設備,這是HTML-5日期選擇是做什麼用的文化。

請注意,您不需要自定義模型聯編程序(日期將以ISO格式發佈,並且將由DefaultModelBinder正確綁定)。

但請注意,HTML-5日期選擇器僅在Chrome和Edge中受支持,並且常規文本框將顯示在Firefox中(例如)。如果你想要一個一致的UI,那麼建議你使用jQuery的datepicker插件(例如jquery-UI),但是你還需要重新配置驗證器以進行客戶端驗證(例如參考this answer)。