【问题标题】:Disable Editor Template Date.cshtml on specific view在特定视图上禁用编辑器模板 Date.cshtml
【发布时间】:2014-12-24 22:35:01
【问题描述】:

我的模特

    [DataType(DataType.Date, ErrorMessage = "Please enter a valid date in the format MM/dd/yyyy")]
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    [Display(Name = "From Date")]
    public DateTime FromDate { get; set; }

我的视图

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

我的 Date.cshtml(编辑器模板)

@Html.TextBox("", string.Format("{0:MM/dd/yyyy}", DateTime.Now),
 new { @class = "datefield", type = "date"  })

我的要求是在这个特定视图上显示数据库值,但每次它都显示当前日期。如何做到这一点请帮助我。

【问题讨论】:

  • 你为什么要将 Date 转换为 String 并再次解析和转换回日期?
  • 我更新了 Date.cshtml 但遇到了同样的问题

标签: asp.net-mvc razor view editortemplates


【解决方案1】:

您应该使用Model 而不是DateTime.Now

@Html.TextBox("", string.Format("{0:MM/dd/yyyy}", Model),
new { @class = "datefield", type = "date"  })

【讨论】:

  • 很好,它工作正常,但在所有其他视图中显示默认 01/01/0001,但我想要当前日期
  • 在所有其他视图中,您必须将模型的属性设置为 DateTime.Now
  • 你能告诉我怎么做吗?
【解决方案2】:

我有针对这种情况的替代解决方案

   @if (@Model.FromDate != null)
    {
        var frmDate = Model.FromDate;
        @Html.EditorFor(model => frmDate)
    }

感谢您的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    相关资源
    最近更新 更多