2011-10-20 72 views
28

我使用ASP.NET MVC 3
我的視圖模型是這樣的:ASP.NET MVC3 - DateTime格式

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

考慮,我有這樣的事情:

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

StartDate以正確的格式顯示,但是當我將其值更改爲19.11.2011並提交表單時,出現以下錯誤消息:「值'19 .11.2011'對於StartDate無效。」

任何幫助將不勝感激!

回答

41

您需要設置正確的文化在你的web.config文件的全球化元素,其dd.MM.yyyy是有效的datetime格式:

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

例如這是在德國的默認格式:de-DE


UPDATE:

根據要保持應用程序的EN-US區域性,但仍使用不同格式的日期的評論部分您的要求。

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); 
    } 
} 

,您將在Application_Start註冊:

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

但我不想用不同的日期時間格式的英文文化。有什麼解決方法嗎? –

+0

@šljaker,是的。您必須編寫自定義模型聯編程序並使用您喜歡的格式手動分析日期參數。 –

+0

全球化標記是標記的子標記。 – encc

10

基於您的評論我看到所有你想要的是一個英文的電流,但具有不同日期這可以通過編寫自定義模型綁定來實現格式(糾正我,如果我錯了)。

事實是DefaultModelBinder使用表單數據的服務器的文化設置。所以我可以說服務器使用「en-US」文化,但使用不同的日期格式。

你可以在Application_BeginRequest這樣做,你就完成了!

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

這一切都不適合我:( – Andrei

+0

謝謝洛特..它爲我工作... –

0

添加了這個下面的代碼的global.asax.cs文件

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<system.web>

<globalization culture="en-US">;