问题
I have a datepicker field
$(function () {
$("#dateTextBox").datepicker({
changeMonth: true,
changeYear: true
});
$("#dateTextBox").datepicker("option", "dateFormat", "dd/mm/yy");
});
In code behind, on button click, I'm trying to set value to datepicker field:
dateTextBox.Value = date.ToString("dd/MM/yyyy");
But after postback, textbox is empty...
回答1:
In order to achieve this, you need to read details from client side using hidden field. This hiddenfield value can be set at server side.
For example:
create hidden field on page
<asp:HiddenField id="hdnDate" runat="server" />
set date string in hiddenField :
protected void button_Clicked (...)
{
DateTime dt = DateTime.Now;
hdnDate.Value = dt.Year.ToString() + "," + (dt.Month - 1 ).ToString() + "," + dt.Day.ToString();
}
now, on document.ready of jquery event, do this
$(document).ready(function() {
$("#dateTextBox").datepicker({
changeMonth: true,
changeYear: true
});
dtString = $("#<%=hdnDate.ClientID%>").val();
dtString = dtString.split(',');
var defaultDate = new Date(dtString[0], dtString[1], dtString[2]);
$("#dateTextBox").datepicker("setDate",defaultDate);
});
回答2:
Try this:
dateTextBox.Value = DateTime.Now.ToString("yyyy-MM-dd");
来源:https://stackoverflow.com/questions/28728434/asp-net-cant-set-value-to-datepicker-from-code-behind