gpt4 book ai didi

c# - MVC3 中模型 DisplayFormat 的 DataFormat 错误

转载 作者:行者123 更新时间:2023-11-30 18:46:56 25 4
gpt4 key购买 nike

这是我根据当前文化设置日期格式的模型。

我尽量避免像 DataFormatString = "{0:MM/dd/yyyy}" 这样的硬编码做下面的原因是为了得到当前的文化模式

 [Required(ErrorMessage = "Date is required")]
[DisplayFormat(ApplyFormatInEditMode = true,
DataFormatString = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString())]
[Display(Name = "Date", ResourceType = typeof(Resources.Global))]
public DateTime Date { get; set; }

在 .cshtml 中

@Html.TextBox("Date", 
Model.Date.ToString("d", System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat), new { @class = "datePicker" })

问题:我收到一个错误

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

有没有办法在 MVC TextBox Helper 中显示基于当前文化的短日期?

最佳答案

{0:d} 是当前文化 ShortDatePattern,

代替

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString())]

你应该使用

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = {0:d})]

设置后,DataFormatString 仅在 EditorFor 和 DisplayFor 中使用。因此,您应该将 View 更改为

@Html.EditorFor(model => model.Date, new { @class = "datepicker" })

记得在 View 顶部添加@model YourModel

关于c# - MVC3 中模型 DisplayFormat 的 DataFormat 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14108880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com