[英]Custom ModelBinder not working for Nullable types
我有以下針對DateTime的自定義ModelBinder:
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult value = null;
try
{
value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return DateTime.ParseExact(value.AttemptedValue, _customFormat, CultureInfo.InvariantCulture);
}
catch (Exception)
{
// If there is a place where DateTime got used which "Bypassed" our EditorTemplate, it means the format will be the default format.
// So let's allow the Model Binder to at least try to Parse the date with the default format.
return DateTime.Parse(value.AttemptedValue);
}
}
如果我在Action中將參數指定為可為null的DateTime( DateTime? dob
),則不會觸發ModelBinder。
如何使ModelBinder在可為空的DateTime上工作?
您需要注冊兩次,如下所示:
ModelBinders.Binders.Add(typeof (DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof (DateTime?), new DateTimeModelBinder());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.