Wednesday, January 11, 2012

Executing Script after asp.net validation and before post back


When we have asp.net validators and a onclick client event enabled on the submit button of a form the validations wont fire if we return something in the javascript funciton we called on the click event.
Ex :
<asp:TextBox runat="server" ID="contactpersonnametextbox" ClientIDMode="Static">               </asp:TextBox>
<asp:RequiredFieldValidator ValidationGroup = "savecontact" ControlToValidate = "contactpersonn  ametextbox" runat = "server" Display = "Dynamic" ErrorMessage = "Enter Name of the Contact" F  oreColor = "Red">
</asp:RequiredFieldValidator>
 <asp:Button runat="server" ID="SaveContactButton" ClientIDMode="Static" Text="Save"
   ValidationGroup = "savecontact" OnClick="SavecontactdetailsbuttonClick"
   OnClientClick = "savecontactdetailsbutton_click();" />

When SaveContactButton is clicked savecontactdetailsbutton_click is called before validations because the html that is rendered would be
<input onclick = 'savecontactdetailsbutton_click();WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$savecontactdetailsbutton", "", true, "savecontact", "", false, false)')>
So if the savecontactdetailsbutton_click function has any return statement, the validations wont execute.If we want the validations to occur as well the custom script to be executed then we have to call the validations explicitly in the script.

function MyButtonOnClientClick()
{
   Page_ClientValidate();
   if(Page_IsValid)
   {
      //do some stuff
      return true;
   }
   else
   {
      return false;
   }
}

Learned this from (http://forums.asp.net/t/1318892.aspx)

No comments:

Post a Comment