简体   繁体   中英

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

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; } }

?

Alternatively, you could decorate the property with DisplayFormatAttribute .

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy HH:MM}")]
public DateTime Date { get { return this.Timestamp.DateTime; } }

The markup you have would not need to change.

If it is read only, you could hardcode as -

<input value="@Model.Date.ToString("dd/MM/yyyy HH:mm")" readonly class="form-control" />

Or display as text

<div class="form-group">
    <label asp-for="Date" class="col-md-2 control-label"></label>
    <div class="col-md-10 form-control-static">
        @Model.Date.ToString("dd/MM/yyyy HH:mm")
    </div>
</div>

尝试这个。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM