【问题标题】:"asp-format" not applied to tag helpers“asp-format”不适用于标签助手
【发布时间】:2016-02-29 13:11:51
【问题描述】:

我在我的 mvc 6 项目中使用带有 taghelper 元素的“asp-format”标签时遇到问题。

这个想法是这样格式化一个日期输入元素:

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

这个“StartDate”属性在我的模型中,这样声明:

public DateTime StartDate {get; set; }

出于一个奇怪的原因,这个元素从来没有被格式化,并且总是这样显示:

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

所以我创建了一个视图模型类并定义了一个属性来保存整个人物模型。

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

在视图中使用这个类,格式化工作。

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

---> 29/02/2016

【问题讨论】:

  • 你有没有使用标签助手解决这个问题?我只是尝试按照您在问题开始时的方式进行操作,并且对我有用。

标签: c# asp.net asp.net-mvc datetime-format


【解决方案1】:

您可以在模型本身中提供格式,例如

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

  public DateTime StartDate {get; set; }

在你看来就像

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

2) 您也可以在模型类中不提供日期格式的情况下这样做

@Html.TextBoxFor(m => m.StartDate, "{0:dd/MM/yyyy}")

【讨论】:

  • 我实际上是在使用带有标签助手方法的 mvc 6,所以我不能使用 html 助手。
  • 我也不喜欢在模型中定义显示格式。如果我想使用相同的模型并以两种不同的格式显示日期(即一个地方有时间,另一个地方没有时间)怎么办?
【解决方案2】:

添加 type = date 来格式化日期

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

【讨论】:

  • 看来type="date"asp-format没有效果)解决了这种情况下的问题,但是一般情况呢?
【解决方案3】:

我不得不使用

[DataType(DataType.Date)]

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

在我的视图模型中。

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

我的观点是这样的:

   From: <input asp-for="From" />

【讨论】:

    猜你喜欢
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2011-10-28
    • 2019-06-16
    相关资源
    最近更新 更多