【问题标题】:Hiding the default value for a date隐藏日期的默认值
【发布时间】:2012-08-21 05:21:05
【问题描述】:

我的视图模型:

public partial class FileTransferFilterCriteriaViewModel
{
    public string Fice { get; set; }
    public string SourceEmail { get; set; }
    public string TargetEmail { get; set; }
    public DateTime FromDate { get; set; }
    public DateTime ToDate { get; set; }
    public string Status { get; set; }
    public string Category { get; set; }
}

(没有来自数据库。)

我的控制器:

return View(new FileTransferFilterCriteriaViewModel())

这是FromDateToDate 显示的内容:

1/1/0001 12:00:00 AM

我的 HTML:

@Html.TextBoxFor(x =>x.Criteria.FromDate)

问题:

  1. 如果日期为null,如何禁止显示默认日期值?
  2. 如果日期不是null,如何将日期格式化为MM/dd/yyyy

【问题讨论】:

    标签: asp.net-mvc-3 datetime html.textboxfor


    【解决方案1】:

    在您的 ViewModel 中使用可为空的日期:

    public DateTime? FromDate { get; set; }
    

    【讨论】:

    • 您还可以将 [required] 属性与可为空的日期时间结合使用
    【解决方案2】:

    我创建了一个编辑器模板,这对我有用。

    视图模型的变化:

    [UIHint(UiHintConstants.DateCalendar)]
            public DateTime? FromDate { get; set; }
    
            [UIHint(UiHintConstants.DateCalendar)]
            public DateTime? ToDate { get; set; }
    

    之后,在 Views/Shared/EditorTemplate 文件夹中创建了一个名为 DateCalendar.chtml 的编辑器模板:

    @using System.Globalization
    @model DateTime?
    
    @Html.TextBox("", (Model.HasValue && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("1900") && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("0001") ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), new { @class = "datePicker", maxlength = "12", size = "12" })
    

    然后将其用作:

    @Html.EditorFor(x =>x.FromDate)
    @Html.EditorFor(x => x.ToDate)
    

    这里是源代码:

    <input class="datePicker" id="Criteria_FromDate" maxlength="12" name="Criteria.FromDate" size="12" type="text" value="" />
    
    <input class="datePicker" id="Criteria_ToDate" maxlength="12" name="Criteria.ToDate" size="12" type="text" value="" />
    

    希望这对其他人有所帮助。

    我无法弄清楚其中的一部分,将 size 和 maxlenth 从模板中移出。在这种情况下,它不相关,但可能会在其他一些情况下变得像我可能会锁定文本框或不想要 jquery 日历。一旦我掌握了这个,我会尽快发布。

    【讨论】:

    【解决方案3】:

    一切正常。但是,您没有从数据库中获取任何数据(通过传入新实例化的视图模型return View(new FileTransferFilterCriteriaViewModel()) 可以证明这一点)。您应该考虑在控制器的操作方法中执行此操作。要获得更短的日期格式,请使用@Html.TextBoxFor(x =&gt;x.Criteria.FromDate.ToShortDateString())

    【讨论】:

    • 这发生在动作内部,只是变得懒惰,只发布了回报。我仍然得到 0001 年 1 月 1 日。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2020-05-23
    • 2012-05-30
    相关资源
    最近更新 更多