簡體   English   中英

DateTime TextBox不為空,如何獲取當前日期

[英]DateTime TextBox is not empty, how to get current date

我有兩個“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”

獲取當前日期,是使用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" })

方式1:

你必須這樣做:

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

方式2:

或者您可以在獲取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" })

使用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 View Engine會為TextBox Editor創建一個id作為模型屬性名稱。 這就是為什么

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

也會工作。 希望這會有所幫助:)

將Date的值與控制器DateTime.Now中的模型一起傳遞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM