Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save raducugheorghe/c312a6ab2195b086c2f6 to your computer and use it in GitHub Desktop.
Save raducugheorghe/c312a6ab2195b086c2f6 to your computer and use it in GitHub Desktop.
[C#][MVC] DateTime model binder that uses EditFormatString for parsing
public class DateTimeWithEditFormatModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(DateTime?) || bindingContext.ModelType == typeof(DateTime))
{
var displayFormat = bindingContext.ModelMetadata.EditFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
return date;
}
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment