2011-10-20 53 views
28

Tôi đang sử dụng ASP.NET MVC 3.
My ViewModel trông như thế này:ASP.NET MVC3 - định dạng DateTime

public class Foo 
{ 
    [DataType(DataType.Date)] 
    [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)] 
    public DateTime StartDate { get; set; } 
    ... 
} 

Theo quan điểm, tôi có một cái gì đó như thế này:

<div class="editor-field"> 
    @Html.EditorFor(model => model.StartDate) 
    <br /> 
    @Html.ValidationMessageFor(model => model.StartDate) 
</div> 

StartDate được hiển thị ở định dạng đúng, nhưng khi tôi thay đổi giá trị thành ngày 19.11.2011 và gửi biểu mẫu, tôi nhận được thông báo lỗi sau: "Giá trị '19 .11.2011 'không hợp lệ cho Ngày bắt đầu".

Bất kỳ trợ giúp nào sẽ được đánh giá rất nhiều!

Trả lời

41

Bạn cần phải thiết lập các nền văn hóa thích hợp trong các yếu tố toàn cầu hóa của file web.config của bạn mà dd.MM.yyyy là một định dạng datetime hợp lệ:

<globalization culture="...." uiCulture="...." /> 

Ví dụ đó là định dạng mặc định trong Đức: de-DE.


UPDATE:

Theo yêu cầu của bạn trong phần ý kiến ​​bạn muốn giữ văn hóa en-US của ứng dụng nhưng vẫn sử dụng một định dạng khác nhau cho ngày tháng. Điều này có thể đạt được bằng cách viết một mô hình tùy chỉnh chất kết dính:

using System.Web.Mvc; 
public class MyDateTimeModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(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); 
      // use the format specified in the DisplayFormat attribute to parse the date 
      if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, 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); 
    } 
} 

mà bạn sẽ đăng ký trong Application_Start:

ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder()); 
+0

Nhưng tôi không sử dụng văn hóa tiếng Anh với định dạng ngày giờ khác nhau. Có bất kỳ công việc xung quanh? –

+0

@ šljaker, đúng vậy. Bạn sẽ phải viết một mô hình tùy chỉnh chất kết dính và phân tích cú pháp tham số ngày bằng cách sử dụng định dạng mà bạn thích. –

+0

Thẻ toàn cầu hóa là con của Thẻ . – encc

10

Dựa trên nhận xét của bạn tôi thấy tất cả các bạn muốn là một tiếng Anh hiện tại nhưng với một ngày khác định dạng (Sửa lỗi nếu tôi sai).

Thực tế là DefaultModelBinder sử dụng cài đặt văn hóa của máy chủ cho dữ liệu biểu mẫu. Vì vậy, tôi có thể nói rằng máy chủ sử dụng văn bản "en-US" nhưng có định dạng ngày khác.

Bạn có thể làm điều gì đó như thế này trong Application_BeginRequest và bạn đã hoàn tất!

protected void Application_BeginRequest() 
{ 
    CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString()); 
    info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy"; 
    System.Threading.Thread.CurrentThread.CurrentCulture = info; 
} 

Web.Config

<globalization culture="en-US" /> 
+1

tất cả đều không hoạt động đối với tôi :( – Andrei

+0

Cảm ơn một lott .. Nó làm việc cho tôi ... –

0

gia tăng này dưới mã để global.asax.cs tập tin

protected void Application_BeginRequest() 
{   
    CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());  
    info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy"; 
    System.Threading.Thread.CurrentThread.CurrentCulture = info;  
} 

Và thêm vào dưới đây để web.config dưới <system.web>

<globalization culture="en-US">; 
Các vấn đề liên quan