Prakash
Prakash

Reputation: 37

Remove Time From DateTime Property in @Html.EditorFor

I want to remove the time from a DateTime property in Razor

@Html.EditorFor(model => model.DATE_OF_BIRTH)

I tried model.DATE_OF_BIRTH.Date,model.DATE_OF_BIRTH.Date.ToShortDateString()

But showing Errors.

Upvotes: 0

Views: 4621

Answers (2)

Nick Boyko
Nick Boyko

Reputation: 21

I had this issue with .Net 6.0. The previous solution didn't worked until I added the [DataType(DataType.Date)] attribute also.

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

@Html.EditorFor(x => x.DATE_OF_BIRTH)

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could decorate your view model property with the [DisplayFormat] attribute:

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

and then the @Html.EditorFor(x => x.DATE_OF_BIRTH) helper will display the value respecting the format you defined.

If you are not using view models and cannot modify your domain model you could use the TextBox helper:

@Html.TextBox("DATE_OF_BIRTH", Model.DATE_OF_BIRTH.ToShortDateString())

Upvotes: 4

Related Questions