Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

asp.net - Entity Framework DateTime format when editing entry

I have a Timetable model which only has two attributes at the moment, an Id and Date. It's defined as so:

public class Timetable
{
    public int Id { get; set; }

    [Required, Column(TypeName = "Date"), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime Date { get; set; }
}

I then scaffolded some basic CRUD functionality, and thanks to the DisplayFormat annotation it's allowing me to create timetables with dates in the dd/MM/yyyy format. However, when I edit an existing timetable, the application is populating the Date text box with 01/01/2015 00:00:00 (see screenshot).

enter image description here

Is there any way to make my application only use the date, rather than date and time?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In order to render the browsers datepicker (<input type="date" ..>) using EditorFor() you need the following attributes on the property (note the ISO format means the date will be displayed in accordance with the browser culture)

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

and in the view

@Html.EditorFor(m => m.Date)

Note the HTML5 date input is not supported in older browsers, and not at all in FireFox - see comparison here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...