9

I created a edit view for a EF Model and have a problem with the datepicker. Whenever i try to edit a `dataset, the edit view don't show me the old date values.

This is my Edit.cshtml Code:

<div class="form-group">
    <label asp-for="BestellungsDatum" class="control-label"></label>
    <input asp-for="BestellungsDatum" type="date" class="form- control" value="@Model.BestellungsDatum" /> 
    <span asp-validation-for="BestellungsDatum" class="text-danger"></span>
</div>

This is what it looks like, but there have to be the old value at this position:

enter image description here

When i change the input to type="text", the value is shown but there is no datepicker.. Any solutions on this?

enter image description here

1
  • You are generating the browsers HTML-5 datepicker (which is not supported in all browsers) which means you must use ISO format - refer this answer Commented Jun 26, 2018 at 11:03

2 Answers 2

26

type="date" generates the browsers HTML-5 datepicker if supported. The specifications require that the value be formatted in ISO format (yyyy-MM-dd) which is then displayed in accordance with the browsers culture.

Add the asp-format to format the value, and remove the value attribute (Tag Helpers correctly generate the value attribute for correct 2-way model binding and you should never attempt to add it yourself)

<input asp-for="BestellungsDatum" type="date" asp-format="{0:yyyy-MM-dd}" class="form-control" /> 

Note the HTML-5 datepicker is not supported in IE, and only in recent versions of FireFox. If you want a consistent UI, then consider using a jQuery datepicker instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the fast answer! This help me a lot.
7

Just like to add an addition to the accepted answer:

<input asp-for="BestellungsDatum" type="date" class="form-control" />

Rather than adding asp-format to the view, add DataFormatString to the data Model or ViewModel, so you don't have to add it to every view that uses it:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.