日期时间的显示格式在 MVC Core 和 bootstrap 4 的编辑模式下不起作用

Display Format for datetime is not working in edit mode in MVC Core and bootstrap 4

我的模型中有一个 DateTime 属性 装饰为

  [Display(Name = "Valid From")]
  [DataType(DataType.Date)]
  [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
  public DateTime ValidFrom { get; set; }

当我在 html 的 table 中使用它时,它的格式呈现正确。这就是我在正确呈现时使用它的方式 - @Html.DisplayFor(modelItem => item.ValidFrom)

它在 edit/create 模式下不工作。这就是脚手架

默认在视图中创建的方式

<input asp-for="ValidFrom" class="form-control" />

当 edit/create 表单加载时它有

已尝试指定明确的日期格式但不起作用

<input asp-for="ValidFrom" class="form-control"  data-date-format="dd-MMM-yyyy"   />

这是它在表单上的呈现方式。您能否指导实际缺少的内容。另外,如何将日期选择器控件的日期格式设置为 dd-MMM-yyyy?

您似乎没有在输入中指定类型

您的日期格式看起来不正确

我发现将 asp-for 与 DateTime 模型属性一起使用存在问题(尽管这些可能适用于字符串值)

这是我在 MVC Core 3 中一直使用的内容。希望这会有所帮助

<input type="date" value="@Model.DateTo.ToHtmlInputDate()" asp-for="DateTo" min="@Model.EarliestDate.ToHtmlInputDate()" max="@Model.LatestDate.ToHtmlInputDate()" onchange="$('form').submit();" class="form-control">

这是我用来扩展 DateTime 的静态助手

public static string ToHtmlInputDate(this DateTime d)
{
    return d.ToString("yyyy-MM-dd");
}
<input asp-for="ValidFrom" class="form-control"  />

通过使用上面的代码,它会生成一个<input type= "date" />元素,默认日期格式是“mm/dd/yyyy”。要更改日期格式,您可以尝试将日期类型更改为文本类型,如下所示:

<input asp-for="ValidFrom" class="form-control" data-date-format="dd-MMM-yyyy" type="text" placeholder="dd-MMM-yyyy" />

然后,输出如下:

然后,当您更改日期时,您可以使用 Bootstrap-datepicker 或 JQuery UI datepicker 到 select 日期并更改日期格式。

[注意]如果你同时使用Bootstrap和JQueryUI,你可能会遇到JQuery冲突错误,这里是 ,你可以查一下。

通过将 false 设置为 DisplayFormat 属性,我可以让它在 .net 6 和 .net 5 MVC 中工作

[DataType(DataType.Date)]
[Display(Name = "Date saisine")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = false)]
public DateTime? Birth {get; set;}