ASP.NET Core 3.1 - Razor View Blank Date Field

Viewed 360

In an ASP.NET Core 3.1 project I have a strange issue with date display in Razor view with model.

Model

[Display(Name = "Date")]
[DataType(DataType.Date)]
[Required(ErrorMessage = "Date is required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/MM/dd}")]
public DateTime ExpenseDate { get; set; }

Date Set in Controller

ne.ExpenseDate = DateTime.Today;

Razor View/Form

@Html.EditorFor(m => m.ExpenseDate, new { htmlAttributes = new { @id = "expenseDate", @class = "form-control", @style = "width: 160px; padding: 4px;" } })

The above is rendered in HTML as follows:

<input class="form-control text-box single-line" data-val="true" data-val-required="Date is required" id="expenseDate" name="ExpenseDate" style="width: 160px; padding: 4px;" type="date" value="2021-05-19" />

Problem

On Desktop/Chrome (debugging) the textbox displays correctly: "19-May-2021"

On Desktop/Chrome (live site), the textbox shows: "dd-----yyyy"

On iPhone and Samsung tablet, nothing is displayed - the textbox is empty.

1 Answers

I made the following changes which appears to have fixed the problem, although I'm not too sure why it now works or why it wasn't working previously:

Changed the DateFormat string in the model to:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]

Changed the code that sets the date in the model to:

ExpenseDate = DateTime.Now.Date;
Related