我有以下模型类:
public sealed class Vignette
{
[Required]
public Guid Id { get; set; }
[DataType(DataType.Date)]
[Required]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime StartDate { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime DueDate { get; set; }
public Notification? Notification { get; set; }
}
这是我的页面用户界面:
<div class="form-floating mb-3 mt-3">
<input asp-for="@Model.Vignette.StartDate" class="form-control" />
<label for="Vignette_StartDate">...</label>
<span asp-validation-for="@Model.Vignette.StartDate" class="text-danger"></span>
</div>
背后的代码:
public void OnGet()
{
Vignette = new Vignette()
{
StartDate = DateTime.Now
};
}
但是显示为(在所有浏览器上:firefox、chrome、brave、edge):
与我在模型中强制执行的格式不同。我希望已经预先填充了默认值(在服务器端设置
OnGet
方法)
我也尝试过:
<input asp-for="@Model.Vignette.StartDate" class="form-control" asp-format="{0:dd-MM-yyyy}"/>
但我也得到同样的结果。
为什么?
浏览器日期控件的格式始终为
yyyy-MM-dd
:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
让控件根据用户的文化来处理格式。
参见 https://www.learnrazorpages.com/razor-pages/forms/dates-and-times
也去掉 asp-for 属性中的
@Model
:
<input asp-for="Vignette.StartDate" class="form-control" />