Prevent postback on server-side property change

ε祈祈猫儿з 提交于 2020-01-25 00:28:09

问题


I have a simple CalendarExtender (from AjaxControlToolkit) attached to a textbox.

<asp:TextBox ID="StartDateText" runat="server" MaxLength="10" Width="70px" AutoPostBack="True" OnTextChanged="StartDateText_TextChanged" />
<asp:ImageButton ID="ImageCalendarStartDate" runat="server" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" />
<asp:CalendarExtender ID="StartDateCalendarExtender" runat="server" TargetControlID="StartDateText" PopupButtonID="ImageCalendarStartDate" />

In order to control user input, I have the AutoPostBack set to True on the textbox, as well as a function on the TextChanged event (although TextChanged isn't the issue here).

In Page_Load, I have:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        StartDateCalendarExtender.SelectedDate = DateTime.Now.AddDays(-1);
    }
}

On opening the page, Page_Load sets the date, but the AutoPostBack triggers a postback right after Page_Load, calling it again with IsPostBack set to true.

Is there a server-side way to prevent this postback?

I tried setting the AutoPostBack property to false, changing the SelectedDate, and setting it back to true, but it keeps firing a postback.


回答1:


The reason is that because you give the date on the extender, then the extender add it to the text box, then the text box trigger the post back.

How about try to set the text at the TextBox at the first place.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // remove that
        // StartDateCalendarExtender.SelectedDate = DateTime.Now;
        // and direct set it to the text box.
        StartDateText.Text = DateTime.Now;
    }
}

Maybe you need to format the DateTime the way you want it.



来源:https://stackoverflow.com/questions/16949410/prevent-postback-on-server-side-property-change

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