Currently I have an ASP.NET Core website and I need to have date field on the form and used this:
<input asp-for="StartDate" class="w-50" type="date" max="2020-10-23" min="1950-01-01" placeholder="dd/mm/yyyy" />
And used on the model the following:
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? StartDate{ get; set; }
For some reason on en-US clients everything is overriden to MM/dd/yyyy.
So the first question would be: can I force the date field to always use the correct format dd/MM/yyyy After searching SO I believe it can't be done, we cannot adjust the client behavior as it would go against the HTML rules.
Then another question comes in my mind. If it can't be done: How can I send the date correct to the backend? I don't care to be honest in what format the user enters the date. But when sending the form in an Ajax call, I need to make sure the date is in dd/MM/yyyy format. Now I use:
jQuery.ajax({
url: `/xxxxxxxx}`,
type: "POST",
data: $("#form").serialize(),
success: function (partialView) {
refreshForm(partialView);
}
});
The .serialize() just sends eg. 31/02/2020 or 02/31/2020 depending on the languange of the browser. I can't changed the API on the backend as it is not mine.
What would you do to fix this? Try to force the input to dd/MM/yyyy, try to parse the date in Javascript before sending(and how then) or even another solution?
I'm happy to hear you solution.
Regards, Miscode