Reputation: 127
I have a model which has a date, when I run my code, it gives me 29/08/2019 00:00:00
. I want it to be 29/08/2019
In my model, I have tried:
[DataType(DataType.Date)]
public DateTime? Date { get; set; }
and
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime? Date { get; set; }
but both seem to not work, I keep getting 29/08/2019 00:00:00
.
I am open to suggestions using the razor page but I do think it's easier to sort this out in the model.
Upvotes: 1
Views: 1603
Reputation: 20106
You need to use
[DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? Date { get; set; }
on the Date
field.
It works well when I use below demo:
Model:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
[DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? Date { get; set; }
}
Index.cshtml.cs
public IList<Student> Student { get;set; }
public async Task OnGetAsync()
{
Student = await _context.Students.ToListAsync();
}
Index.cshtml
@foreach (var item in Model.Student) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@item.Date.Value.ToString("dd/MM/yyyy")
@*or below*@
@Html.DisplayFor(modelItem => item.Date)
</td>
</tr>
}
Upvotes: 2