0

I have the following datetime field

    [DisplayName("Expiry Date")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime ExpiryDate { get; set; }

And then I display it like so (top line is me checking I actually have a value for ExpiryDate - it displays as I would expect)

<div>
     Current value: @Model.ExpiryDate.ToShortDateString()
     @Html.TextBoxFor(model => model.ExpiryDate, "{0:dd/MM/yyyy}" , new { type = "date", @class = "form-control" })
</div>

The date picker (in Chrome) works correctly for selecting a date - I can select a date and it correctly binds back to my model on submit. It also works fine when ExpiryDate doesn't have a value, displaying "dd/mm/yyyy"

But when ExpiryDate does have a value, the textbox still displays dd/mm/yyyy rather than 22/02/2019 or whatever the value is

Strangely, the textbox appears to have the correct value when I inspect the generated HTML, as below

<input class="form-control" data-val="true" data-val-date="The field Expiry Date must be a date." data-val-required="The Expiry Date field is required." id="ExpiryDate" name="ExpiryDate" type="date" value="22/02/2019">

I've also tried explicitly including the value, including @value = Model.ExpiryDate.ToShortDateString() in the HtmlAttributes, which makes no difference (not that I particularly expected it to, since the value is already correct)

What am I missing?

Jon Story
  • 2,881
  • 2
  • 25
  • 41
  • As you use `date` from HTML5, I think you need to look at https://stackoverflow.com/questions/7372038/is-there-any-way-to-change-input-type-date-format for example; basically data format is hardcoded, and presentation format is client-specific – Lanorkin Feb 25 '19 at 07:12

1 Answers1

0

While I haven't tested, I think that the problem is that the value should respect not your display format, but the standard for HTML, so assigning "02/22/2019" should work (in ASP.NET you probably need to use InvariantCulture when assigning to convert the value).

Ivan Ičin
  • 9,672
  • 5
  • 36
  • 57