"asp-format" not applied to tag helpers
Asked Answered
I

4

19

I'm facing a problem using "asp-format" tag with taghelper element in my mvc 6 project.

The idea is to format a date input element this way:

<input asp-for="StartDate" asp-format="{0:dd/MM/yyyy}" />

This "StartDate" property is in my model, declared this way:

public DateTime StartDate {get; set; }

For a strange reason, this element is never formatted, and is presented always like this:

---> 02/29/2016 00:00:00

So I created a viewmodel class and defined a property to hold the entire person model.

public class PersonViewModel 
{
    public Person Johndoe {get; set; }
}

And using this class in the view, the formatting works.

<input asp-for="Johndoe.StartDate" asp-format="{0:dd/MM/yyyy}" />

---> 29/02/2016
Inaccuracy answered 29/2, 2016 at 13:11 Comment(1)
Did you ever get a resolution for this using the tag helpers? I just tried doing it the way you have at the start of the question and it worked for me.Pritchard
N
8

You can provide the format in model itself like

 [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]

  public DateTime StartDate {get; set; }

and in your view simply like

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

2) You can also do this without providing date format in model class

@Html.TextBoxFor(m => m.StartDate, "{0:dd/MM/yyyy}")
Nev answered 29/2, 2016 at 13:39 Comment(2)
I'm actually using mvc 6 with tag helpers approach, so I cant use html helpers.Inaccuracy
I'm also not a big fan of defining the display format in the model. What if I want to use the same model and display the date in two different formats (i.e. with the time in one place and without the time in another).Pritchard
P
4

Add type = date which will format the date

<input asp-for="StartDate" type="date" class="form-control" />
Pena answered 7/1, 2019 at 19:47 Comment(2)
It seems that type="date" (asp-format has no effect) fixes the problem in this case, but what about in general?Biogeochemistry
"In general", these are two entirely different approaches. type=date will format the date in the user's chosen format. The asp-format approach formats it in the developer's choice.Layette
N
0

I had to use

[DataType(DataType.Date)]

and

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]

In my viewmodel.

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

My view looks like this:

   From: <input asp-for="From" />
Nydianye answered 13/12, 2019 at 10:16 Comment(0)
V
0

asp-format worked with me only when I added [DataType(DataType.Text)]

This will render the input as text not date or datetime, native browser date picker will not appear, but you can use third party date picker, for example bootstrap-datepicker

Volz answered 19/2, 2023 at 21:23 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.