私自身もこの非常に大きな問題を抱えていました。何時間も試して失敗した後、あなたが尋ねたような実用的な解決策が得られました。
まず第一に、プロパティだけにバインダーを設定することは不可能なので、yuoは完全なModelBinderを実装する必要があります。すべての単一のプロパティをバインドするのではなく、気になるものだけをバインドする必要があるため、DefaultModelBinderから継承して、単一のプロパティをバインドできます。
public class DateFiexedCultureModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.PropertyType == typeof(DateTime?))
{
try
{
var model = bindingContext.Model;
PropertyInfo property = model.GetType().GetProperty(propertyDescriptor.Name);
var value = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
if (value != null)
{
System.Globalization.CultureInfo cultureinfo = new System.Globalization.CultureInfo("it-CH");
var date = DateTime.Parse(value.AttemptedValue, cultureinfo);
property.SetValue(model, date, null);
}
}
catch
{
//If something wrong, validation should take care
}
}
else
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
}
私の例では、複雑な文化で日付を解析していますが、あなたがやりたいことは可能です。CustomAttribute(DateTimeFormatAttributeなど)を作成し、それをプロパティの上に置く必要があります。
[DateTimeFormat("d.M.yyyy")]
public DateTime Birth { get; set,}
これで、BindPropertyメソッドで、DateTimeプロパティを探す代わりに、DateTimeFormatAttributeでプロパティを探し、コンストラクターで指定した形式を取得して、DateTime.ParseExactで日付を解析できます。
これがお役に立てば幸いです。このソリューションを導入するのに非常に長い時間がかかりました。検索方法がわかれば、このソリューションを手に入れるのは実際には簡単でした:(