简体   繁体   中英

“asp-format” not applied to tag helpers

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

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}")

添加 type = date 将格式化日期

<input asp-for="StartDate" type="date" class="form-control" />

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" />

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