After first postback, why I have to click the button twice for postback to occur?

In one of my recent project I came across an issue where after my first postback I had to click the button twice for next postback to occur.

Scenario

It was a form I was working on. It has few textboxes, dropdownlists and some validation controls attached to them and a Submit and Clear button. All these controls are inside ASP.NET Updatepanel.

I also have a custom javascript that shows validation messages like the asp.net Ajax ValidatorCalloutExtender. The dropdownlist on the form had AutoPostBack=”true”. Now if I click the postback Submit button, and if there were some errors on textboxes and dropdownlists. Say now I do some selection in the dropdownlist, there will be a postback since they are set to autopostback and all the validation messages will be wiped out.

To preserve those validation messages after partial postback from the dropdownlist, in the endRequest handler for the PageRequestManager I was doing something like this:

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);

function endRequest(sender, args)

{ 
        if(validation had failed prior to partialpostbak then upon return manually validate the form )

       { 
            if (typeof (Page_ClientValidate) != "undefined")

          { 
                    Page_ClientValidate(); 
           } 
        }

}

The above code worked fine and would display the validation errors even after postback from the dropdownlist.

But now if I click the Clear button(has CausesValidation=”false”) that would do a postback to clear the form controls, I had to click it twice. First one did nothing and second would do a postback and clear the form.

Cause

I knew it was something related to validation but took me sometime to get there. After setting breakpoints in the javascript files emitted by ASP.NET, I saw a variable (Page_BlockSubmit ) that was set to “true” and it was blocking the postback on the first click.

So in the endRequest when I called the Page_ClientValidate and some controls failed to validated the variable Page_BlockSubmit is set to true. That would prevent the postback. When I clicked the Clear button first time, the postback would be prevented but Page_BlockSubmit was reset to false. So on next click button would do the postback.

Solution

I simply had to explicitly reset the Page_BlockSubmit =false in my endRequest after calling the Page_ClientValidate();

function endRequest(sender, args)

{ 
        if(validation had failed prior to partialpostbak then upon return manually validate the form )

       { 
            if (typeof (Page_ClientValidate) != "undefined")

          { 
                    Page_ClientValidate();

                   Page_BlockSubmit =false; 
           } 
        }

}

Hope this helps someone in similar situation.

1 Comment

Comments have been disabled for this content.