2011-06-20 2 views
3

私は、現在のカルチャに従ってURL文字列(GET)から来る日付をマップするはずのカスタムモデルバインダーを書いています(ここでの脇役:GETをhttpとして使用するとデフォルトのモデルバインダーは現在のカルチャを考慮しません) -コール...)。カスタムモデルバインダーからデフォルトモデルバインダーを呼び出しますか?

public class DateTimeModelBinder : IModelBinder 
{ 

    #region IModelBinder Members 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 

     if (controllerContext.HttpContext.Request.HttpMethod == "GET") 
     { 
      string theDate = controllerContext.HttpContext.Request.Form[bindingContext.ModelName]; 
      DateTime dt = new DateTime(); 
      bool success = DateTime.TryParse(theDate, System.Globalization.CultureInfo.CurrentUICulture, System.Globalization.DateTimeStyles.None, out dt); 
      if (success) 
      { 
       return dt; 
      } 
      else 
      { 
       return null; 
      } 
     } 

     return null; // Oooops... 

    } 
    #endregion 
} 

私は、Global.asaxの中にモデルバインダーを登録:

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

今の問題は、最後のreturn null;で発生します。 POSTで他のフォームを使用すると、すでにマップされている値がnullで上書きされます。どうすればこれを避けることができますか?

任意の入力に対してThx。 sl3dg3

答えて

3

まあ、それは実際には自明な解である:私は、既定のバインダーの新しいインスタンスを作成して、彼にタスクを渡す:

public class DateTimeModelBinder : IModelBinder 
{ 

#region IModelBinder Members 
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
{ 

    if (controllerContext.HttpContext.Request.HttpMethod == "GET") 
    { 
     string theDate = controllerContext.HttpContext.Request.Form[bindingContext.ModelName]; 
     DateTime dt = new DateTime(); 
     bool success = DateTime.TryParse(theDate, System.Globalization.CultureInfo.CurrentUICulture, System.Globalization.DateTimeStyles.None, out dt); 
     if (success) 
     { 
      return dt; 
     } 
     else 
     { 
      return null; 
     } 
    } 

    DefaultModelBinder binder = new DefaultModelBinder(); 
    return binder.BindModel(controllerContext, bindingContext); 

} 
#endregion 
} 
3

DefaultModelBinderから派生して、基本メソッドを呼び出す:

public class DateTimeModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     // ... Your code here 

     return base.BindModel(controllerContext, bindingContext); 
    } 

} 
+0

他に選択肢はありませんか?もっと一般的な目的のために 'DefaultModelBinder'から別のバインダーを既に得ました。 – sl3dg3

+0

@ sl3dg3、 'DefaultModelBinder'から派生した問題は何ですか?これはDateTimeフィールドにのみ使用されます。これは、これが登録される方法です。 –

+0

正確には、それは 'DateTime'型に関するものです。私は、現在のカルチャを認識しているURL文字列でdatetime-valueを作成したいと思います...私は、DefaultModelBinderから派生した既存のバインダークラスにそれを含める方が良いでしょう。 – sl3dg3

関連する問題