ASP.NET Can't set value to datepicker from code behind

孤街醉人 提交于 2019-12-11 23:49:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!