2010-11-30 25 views
1

是來自POST正確綁定日期時間的一個不同的格式(根據我的電腦的格式)來自搞定不的DateTime使用比來自POST

但DateTime值綁定正確,它使用不同的格式

my format is dd.MM.yyyy, in GET it uses MM.dd.yyyy instead 

I don't have this problem if I use the en-US format (which is MM/dd/yyyy) 

任何人都知道如何解決這個問題?

這是一個mvc錯誤? (它不考慮綁定獲取請求時的文化)

+0

您是否測試過來自多個瀏覽器的應用程序以查看該行爲是否不變? – rjzii 2010-11-30 14:02:57

+0

@Rob,不,我沒有,但我會,thnx建議 – Omu 2010-11-30 14:38:45

回答

8

不,看起來這不是一個錯誤。你可以在這裏得到更多的細節:MVC DateTime binding with incorrect date format

我一直在使用下面的ModelBinder來解決這個問題。

public class CurrentCultureDateTimeBinder : IModelBinder 
{ 
    private const string PARSE_ERROR = "\"{0}\" is not a valid date"; 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 

     if (valueProviderResult == null) return null; 

     var date = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue; 

     if (String.IsNullOrEmpty(date)) 
      return null; 

     bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName)); 

     try 
     { 
      return DateTime.Parse(date); 
     } 
     catch (Exception) 
     { 
      bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format(PARSE_ERROR, bindingContext.ModelName)); 
      return null; 
     } 
    } 
} 

希望它有幫助。