asp.net-core.net-corebootstrap-4asp.net-core-mvcbootstrap-datetimepicker

Display Format for datetime is not working in edit mode in MVC Core and bootstrap 4


I have a DateTime property in my model decorated as

  [Display(Name = "Valid From")]
  [DataType(DataType.Date)]
  [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
  public DateTime ValidFrom { get; set; }

When I am using it in html's table's td its format is rendering correctly. This is how I am using it when it renders correctly - @Html.DisplayFor(modelItem => item.ValidFrom)

Its not working in edit/create mode. This is how it created in view by default by scaffolding

<input asp-for="ValidFrom" class="form-control" />

When edit/create form loads it has

Tried by specifying explicit date format but not working

<input asp-for="ValidFrom" class="form-control"  data-date-format="dd-MMM-yyyy"   />

enter image description here

This is how it renders on the form. Can you please guide what actually missing. Also, how can I set date format of date picker control to dd-MMM-yyyy?


Solution

  • <input asp-for="ValidFrom" class="form-control"  />
    

    By using above code, it will generate a <input type= "date" /> element, by default the date format is "mm/dd/yyyy". To change the date format, you could try to change the date type to text type, like this:

    <input asp-for="ValidFrom" class="form-control" data-date-format="dd-MMM-yyyy" type="text" placeholder="dd-MMM-yyyy" />
    

    Then, the output as below:

    enter image description here

    Then, when you change the date, you could use Bootstrap-datepicker or JQuery UI datepicker to select date and change the date format.

    [Note] If you are using both Bootstrap and JQuery UI, you might meet the JQuery conflict error, here is a similar thread, you could check it.