Specify a format for "asp-for" HTML Tag (ASP.NET Core)

Viewed 23080

In an ASP.NET Core project I have to display a (readonly) date in a specific format (say "dd/mm/yyyy HH:MM")

<div class="form-group">
    <label asp-for="Date" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="Date" readonly class="form-control" />
    </div>
</div>

How can I do it, knowing that the Date field is declared in the model like this

public DateTime Date { get { return this.Timestamp.DateTime; } }

?

4 Answers

Try this.

<input asp-for="Date" asp-format="{0:dd/MM/yyyy HH:mm}" readonly class="form-control" />

Using ASP.Core TagHelpers as per your question;

[DataType(DataType.Date)]
public DateTime Date { get { return this.Timestamp.DateTime; } }

will format the input fields nicely in accordance with your locale setting. I haven't found a tag helper solution for any other tags, looks like hardcoding as per Win's answer

Related