ASP.NET AJAX Toolkit - 在Postback上重置CalendarExtender

use*_*192 10 asp.net calendarextender

我有一个ASP.NET页面,它有两个输入元素:

  1. 一个ReadOnly的TextBox.此TextBox是CalendarExtender的TargetControl
  2. 具有AutoPostBack = true的DropDownList

这是代码:

<table border="0" cellpadding="0" cellspacing="0">
  <tr><td colspan="2">Date:</td></tr>
  <tr><td colspan="2">
    <asp:TextBox ID="dateTextBox" runat="server" ReadOnly="true" />
    <ajax:CalendarExtender ID="datePicker" runat="server" Format="MM/dd/yyyy" OnLoad="datePicker_Load" TargetControlID="dateTextBox" />
  </td></tr>

  <tr><td colspan="2">Select an Option:</td></tr>
  <tr>
    <td>Name:&nbsp;</td>
    <td><asp:DropDownList ID="optionsDropDownList" runat="server" AutoPostBack="true"  
      OnLoad="optionsDropDownList_Load" 
      OnSelectedIndexChanged="optionsDropDownList_SelectedIndexChanged" 
      DataTextField="Name" DataValueField="ID" />
  </td></tr>

  <tr><td><asp:Button ID="saveButton" runat="server" Text="Save" OnClick="saveButton_Click" /></td></tr>
</table>
Run Code Online (Sandbox Code Playgroud)

当DropDownList回发时,用户使用datePicker选择的日期将重置为当前日期.另外,如果我查看dateTextBox的Text属性,它等于string.Empty.

如何保留用户在PostBack上选择的日期?

小智 12

当然你必须像其他人已经建议的那样做:readonly动态设置字段而不是标记,并确保Page_Load()在回发期间不会意外重置值...

...但你必须在里面执行以下操作Page_Load(),因为该CalendarExtender对象具有必须强制更改的日期的内部副本:

if (IsPostBack)  // do this ONLY during postbacks
{
    if (Request[txtDate.UniqueID] != null)
    {
        if (Request[txtDate.UniqueID].Length > 0)
        {
            txtDate.Text = Request[txtDate.UniqueID];
            txtDateExtender.SelectedDate = DateTime.Parse(Request[txtDate.UniqueID]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*nes 11

文本框是只读的这一事实似乎导致了这个问题.我在任何绑定事件中都没有使用代码复制您的问题,并且日期仍然消失.但是,当我将文本框更改为ReadOnly = False时,它工作正常.您是否需要将文本框设置为只读,还是可以禁用它或验证输入的日期?

编辑:好的,我有一个答案给你.根据此论坛问题,只读控件不会发回服务器.因此,当您进行回发时,您将失去只读控件中的值.您将不需要将控件设为只读.

  • Downvoting因为我相信@ taeda的答案是这个问题的真正答案. (3认同)