I'm having a problem with an input field switching between type=text (when it's not focused) and type=date (when it's focused). I'm using .NET Core 3.1 framework.
Model:
public class DocumentVersionModel
{
public int Id { get; set; }
public int DocumentModelId { get; set; }
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime CreationDate { get; set; }
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime LastChangeDate { get; set; }
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DocumentDate { get; set; }
public string Content { get; set; }
public int Version { get; set; }
public DocumentModel Document { get; set; }
}
The format yyyy-MM-dd
is needed for the database and is the one displayed when the input field isn't focused. The format I need to display the dates is mm/dd/yyyy
, but I can't change the DateFormatString
(and removing ApplyFormatInEditMode = true
didn't work).
This is the form in the RazorPage:
<form asp-action="Edit">
<br />
<div class="row justify-content-center">
<div class="col-12 form-group">
<label>Titolo</label>
<input asp-for="Title" class="form-control" />
</div>
<div class="col">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" id="iddoc" />
<div class="form-group">
<label>Data Documento</label>
<input asp-for="DocumentVersion.FirstOrDefault(q => q.Version==Model.ActiveVersion).DocumentDate" class="form-control" />
<span asp-validation-for="DocumentVersion.FirstOrDefault(q => q.Version==Model.ActiveVersion).DocumentDate" class="text-danger"></span>
</div>
<div class="form-group">
<label>Data Creazione</label>
<input asp-for="DocumentVersion.FirstOrDefault(q => q.Version==Model.ActiveVersion).CreationDate" class="form-control" readonly="readonly" />
</div>
<div class="form-group">
<label>Data Ultima Modifica</label>
<input asp-for="DocumentVersion.FirstOrDefault(q => q.Version==Model.ActiveVersion).LastChangeDate" class="form-control" readonly="readonly" />
</div>
</div>
</form>
A little note about the form: if I use type="date"
or "datetime"
inside the input tag, the type keeps changing between text and date, but if I use "datetime-local"
is shown correctly (but it displays the time too which I don't need).
This is the GIF of what happens:
https://i.stack.imgur.com/LzQaS.jpg
This is the very bad and inefficient jQuery solution I used to "fix" the problem:
$('#DocumentDate, #LastChangeDate, #CreationDate').attr('type','date'); //when the page loads
$(document).click(function () {
if ($('#DocumentDate').not(':focus') || $('#LastChangeDate').not(':focus') || $('#CreationDate').not(':focus'))
$('#DocumentDate, #LastChangeDate, #CreationDate').attr('type','date');
});