【问题标题】:Model DisplayFormat's DataFormat Error in MVC3MVC3 中模型 DisplayFormat 的 DataFormat 错误
【发布时间】:2012-12-16 01:01:36
【问题描述】:

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

我尽量避免像 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" })

问题:我收到一个错误

属性参数必须是常量表达式 typeof 属性参数类型的表达式或数组创建表达式

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

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 razor


    【解决方案1】:

    {0:d}是当前文化ShortDatePattern

    而不是

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

    你应该使用

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

    设置后,DataFormatString 仅用于 EditorFor 和 DisplayFor。因此,您应该将视图更改为

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

    记得在视图顶部添加@model YourModel

    【讨论】:

    • @Html.EditorFor(model => model.Date, new { @class = "datepicker" }) 不起作用 - 第二个参数是附加视图数据,而不是 html 属性!检查EditorFor documentation
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多