I am struggling with this for hours, I have model with this property
public DateTime ValidTo { get; set; }
I display this property in View with changed format
@Html.TextBoxFor(m => Model.ValidTo, "{0:dd.MM.yyyy}" })
And the problem begin when I submit the form,
because the property Model.ValidTo
has now value dd/MM/yyyy
. The day and month switched position. It should be MM/dd/yyyy
.
How to map my custom date format in the view to the date format in the model ? Can I set custom date format in the model ? I cannot set culture for the whole page, I need to do it only for one model or better do it to specific datetime property in the model.
Any idea ?
Experiment 1 - Custome Model Data Binder - Does not work
I tried solution from this answer DisplayFormat ApplyFormatInEditMode
[DateTimeFormat(Format = "dd.MM.yyyy")]
public DateTime ValidTo { get; set; }
public class DateTimeFormatAttribute : ValidationAttribute
{
public string Format { get; set; }
public override bool IsValid(object value)
{
if (value == null)
return true;
DateTime val;
try
{
val = DateTime.ParseExact(value.ToString(), Format, null);
}
catch (FormatException)
{
return false;
}
//Not entirely sure it'd ever reach this, but I need a return statement in all codepaths
return val != DateTime.MinValue;
}
}
but in the View, default datetime format is displayed and after submitting dd.MM.yyyy
format, the model behave the same.