15 February 2013

Dropdown list autopostback not working when validators fire

The Dropdown server control of the webforms can automatically post back by setting the autopostback property to true and setting the change event.
It works as expected, except when you have validators on the form with client-side validation active. The post back causes the validators to fire and prevent the autopostback if the form is invalid.

If there is the need to post back even if the form is invalid, the Microsoft documentation states that the CausesValidation property must be set to false.
However the issue still persists and the client side onchange event must execute the code Page_BlockSubmit=false
Page_BlockSubmit controls whether the form should be submitted or not.
Here is a full example:

<asp:dropdownlist autopostback="true" 
                 causesvalidation="false"
                 id="myDropDown" 
                 onchange="Page_BlockSubmit = false;"
                 onselectedindexchanged="myDropDown_SelectedIndexChanged"
                 runat="server">  
</asp:dropdownlist>

Note that to apply the best practices the client side event onchange should be set on the code behind.
myDropDown.Attributes.Add("onchange", "myDropDownOnchange();");
function myDropDownOnchange() {
    Page_BlockSubmit=false;
}

2 comments:

Anonymous said...

nice. thanks for the solution.

Anonymous said...

Thanks!

This solution worked great.