Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

?

like image 729
serge Avatar asked Jul 19 '17 17:07

serge


People also ask

What is ASP for in HTML?

ASP stands for Active Server Pages. ASP is a development framework for building web pages. ASP supports many different development models: Classic ASP.

What is the default layout for an ASP.NET Core app known as?

By default, every layout must call RenderBody . Wherever the call to RenderBody is placed, the contents of the view will be rendered.

What is ASP for tag helper?

A Tag Helper Component is a Tag Helper that allows you to conditionally modify or add HTML elements from server-side code. This feature is available in ASP.NET Core 2.0 or later. ASP.NET Core includes two built-in Tag Helper Components: head and body . They're located in the Microsoft.


3 Answers

Try this.

<input asp-for="Date" asp-format="{0:dd/MM/yyyy HH:mm}" readonly class="form-control" />
like image 148
tsu1980 Avatar answered Sep 28 '22 21:09

tsu1980


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.

like image 22
Will Ray Avatar answered Sep 28 '22 21:09

Will Ray


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

like image 37
RichyRoo Avatar answered Sep 28 '22 21:09

RichyRoo