【问题标题】:DateTime TextBox is not empty, how to get current dateDateTime TextBox 不为空,如何获取当前日期
【发布时间】:2015-09-08 10:42:14
【问题描述】:

我有两个“Html.TextBoxFor”链接到模型字段(强类型)。在页面加载时,它会在文本框中显示值 0001-01-01 00:00:00。我想以“dd-MM-yyyy”格式获取当前日期并将其放入文本框中。因此,当您加载页面时,应该会看到日期 08-09-2015。

为此,我需要更改格式。到目前为止,我尝试的是添加这行代码:

[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]

在我的模型中的字段上。这确实有效,但在页面加载时,文本框仍然有 "0001-01-01 00:00:00",而不是 "0001-01-01" p>

还要获取当前日期,是用Jquery最好的方法吗?

文本框的一些代码

 <label>Departure date</label>
 <br />
 @Html.TextBoxFor(m => m.DepartureDate, new { @class = "textbox" })
 <label>Return date</label>
 <br />
 @Html.TextBoxFor(m => m.ReturnDate, new { @class = "textbox" })

【问题讨论】:

    标签: c# jquery html datetime


    【解决方案1】:

    方式一:

    你必须这样做:

    @Html.TextBoxFor(m => m.DepartureDate, new { 
                                                 Value=Model.DepartureDate == DateTime.MinValue ? DateTime.Now.ToString("dd-MM-yyyy") : Model.DepartureDate  ,
                                                 @class = "textbox" 
                                               })
    

    方式二:

    或者您也可以在获取您的 Model 属性时这样做:

    private DateTime _departureDate
    public DateTime DepartureDate
    {
      get
      {
         return _departureDate == DateTime.MinValue ? DateTime.Now : _departureDate; 
    
      }
    
      set
      {
        _departureDate = value;
      }
    }
    

    然后你现在不需要使用Value 属性,你必须写和你的OP一样:

     @Html.TextBoxFor(m => m.DepartureDate, new { @class = "textbox" })
    

    【讨论】:

    • 有没有办法可以在当天添加 +1 天?如果我想在当天之后的第二天?
    • @Mikkel 是的,您可以在DateTime.Now 之后致电AddDays(1),例如:DateTime.Now.AddDays(1)
    【解决方案2】:

    使用jQuery也是一个很好的解决方案,同时会丰富UI。

    用jQuery代码会是这样的,

    <label>Departure date</label>
    <br />
    @Html.TextBoxFor(m => m.DepartureDate, new { @class = "textbox",@id="datepicker" })
    <label>Return date</label>
    <br />
    @Html.TextBoxFor(m => m.ReturnDate, new { @class = "textbox" })
    

    添加以下脚本和样式:

    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
    $(function () {  
    $("#datepicker").datepicker(); 
    $("#ReturnDate").datepicker();  
    });
    </script>
    

    Razor 视图引擎默认为 TextBox Editor 创建一个 id 作为模型属性名称。这就是为什么

     $("#ReturnDate").datepicker();
    

    也可以。 希望这会有所帮助:)

    【讨论】:

      【解决方案3】:

      从控制器 DateTime.Now 传递 Date 的值和模型。

      【讨论】:

        猜你喜欢
        • 2017-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多