5

特定のDateTime Modelプロパティに「リモート」検証属性を使用しているときに、不審な動作が発生しました。DateTimeのMVCモデルのバインドがGETまたはPOSTを使用して異なる

サーバー側後述のように、私のアプリケーションの文化が定義されている:

protected void Application_PreRequestHandlerExecute() 
{ 
    if (!(Context.Handler is IRequiresSessionState)){ return; } 
    Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-BE"); 
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl-BE"); 
} 

クライアント側後述のように、私のアプリケーションの文化が定義されています

Globalize.culture("nl-BE"); 

ケース1:

  • モデルプロパティ

    [Remote("IsDateValid", "Home")] 
    public DateTime? MyDate { get; set; } 
    
  • コントローラーアクション

    public JsonResult IsDateValid(DateTime? MyDate) 
    { 
        // some validation code here 
        return Json(true, JsonRequestBehavior.AllowGet); 
    } 
    
  • IsDateValid方法をデバッグしながら、05/10/2013としてUIに入力された日付(10月5日2013)10/05/2013(5月10日、2013)
として解釈 誤っです

ケース2:

  • モデルプロパティ

    [Remote("IsDateValid", "Home", HttpMethod = "POST")] 
    public DateTime? MyDate { get; set; } 
    
  • コントローラーアクション

    [HttpPost] 
    public JsonResult IsDateValid(DateTime? MyDate) 
    { 
        // some validation code here 
        return Json(true); 
    } 
    
  • IsDateValid方法をデバッグしながら、05/10/2013としてUIに入力された日付(10月5日2013)05/10/2013(10月5日と解釈正しくです2013)

makの設定がありません必要に応じて「標準的な」GETリモート検証作業を行いますか?

+0

デバッグ –

答えて

8

GET用のデータをバインドする場合はInvariantCulture( "en-US")が使用されますが、POST Thread.CurrentThread.CurrentCultureの場合はInvariantCultureが使用されます。その理由は、GET URLがユーザーによって共有される可能性があるため、不変である必要があります。 POSTは共有されませんが、サーバーのバインディングにはサーバーのカルチャを使用するのが安全です。

あなたのアプリケーションに、異なる国から来た人々の間でURLを共有するオプションが必要ないと確信できる場合は、自分自身でを作成してもGETリクエストでもサーバーのロケールを使用するようにしてください。ここで

は、Global.asax.csのように見えるかもしれませんどのようにサンプルがある:ビューで日付を解析するために使用されているどのような文化

protected void Application_Start() 
{ 
    /*some code*/ 

    ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder()); 
    ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder()); 
} 

/// <summary> 
/// Allows to pass date using get using current server's culture instead of invariant culture. 
/// </summary> 
public class DateTimeModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
     var date = valueProviderResult.AttemptedValue; 

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

     bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult); 

     try 
     { 
      // Parse DateTimeusing current culture. 
      return DateTime.Parse(date); 
     } 
     catch (Exception) 
     { 
      bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid.", bindingContext.ModelName)); 
      return null; 
     } 
    } 
} 
関連する問題