Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date input tag helper is not showing the date from database

When I use the following code in my edit view, it doesn't show the date from the model.

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

the property of the model is declared like this:

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

and the value is passed over in the model

Picture of the model passed

Why isn't this working?

like image 342
Tirdyr Avatar asked Feb 16 '17 13:02

Tirdyr


People also ask

How do I display a date field in HTML?

The <input type="date"> defines a date picker. The resulting value includes the year, month, and day.


2 Answers

Here is the solution to my problem

https://forums.asp.net/t/2167833.aspx?Date+control+is+not+showing+value+from+model

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

ApplyFormatInEditMode = false

like image 117
Matías Gallegos Avatar answered Oct 21 '22 22:10

Matías Gallegos


The problem is that attribute [DataType(DataType.Date)] on your model property makes the input tag helper produce type="date" HTML attribute, which in HTML5 causes fixed, standard format - see information here: Is there any way to change input type="date" format?

In order to display the field with proper format, remove [DataType(DataType.Date)] attribute and you will be fine. Additionaly, in order to have forward slashes in date format, you need to escape them like this:

[DisplayFormat(DataFormatString = @"{0:dd\/MM\/yyyy}", ApplyFormatInEditMode = true)]
public DateTime OprettetDato { get; set; }

If you want to have custom date format with datepicker, you need to use some custom JavaScript solution.

Update: Later versions of tag helpers default to the input date type if the model property is a DateTime object. To allow a custom date format ensure that the html input type is text by adding [DataType(DataType.Text)]

like image 11
Marcin Zablocki Avatar answered Oct 21 '22 22:10

Marcin Zablocki