Search code examples
c#asp.netajaxajaxcontroltoolkitmodalpopupextender

Required field Validation and Modal popup occurs at the same time


I have a page where there are some text box with required fields and I have a submit button in the same page for which I have the Modal Pop up. When I click the submit button without filling the text box, the pop up is displayed and the error message is also displayed near the text box.

<asp:TextBox ID="txt_ExpiresBy"
             class="datePicker" 
             runat="server" />
<asp:RequiredFieldValidator ID="req_ExpiresBy" 
                            ValidationGroup="SM" 
                            runat="server" 
                            ControlToValidate="txt_ExpiresBy" 
                            Text="*ExpiresBy is a required field.">
</asp:RequiredFieldValidator>
<asp:Button ID="btn_Send" 
            runat="server" 
            ValidationGroup="SM" 
            Text="Send" 
            CausesValidation="true" 
            OnClick="Send_Click" />                         
<asp:ModalPopupExtender ID="ModalPopupExtender1" 
                        TargetControlID="btn_Send" 
                        PopupControlID="Pnl_ForgotPass" 
                        runat="server">
</asp:ModalPopupExtender>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Panel ID="Pnl_ForgotPass" runat="server" 
           CssClass="cpHeader">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Button ID="Btn_ViewDash" runat="server" 
                        Text="View DashBoard" />
            <asp:Button ID="Btn_SeeMessages" runat="server" 
                        Text="Messages Page" />
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Panel>

I want to display the PopUp only after all the required fields are filled, but it displays before it. How to change it.


Solution

  • You could do this with some javascript.

    First remove the TargetControlID="btn_Send" from ModalPopupExtender1

    <asp:ModalPopupExtender ID="ModalPopupExtender1" 
                        PopupControlID="Pnl_ForgotPass" 
                        runat="server">
    

    Then, Add those scripts at the end of the page.

    <script type="text/javascript">
      function ShowPopup() {
       $find('ModalPopupExtender1').Show();
      }
    
      function ValidateAndShowPopup() {
        if (Page_ClientValidate('SM')) {
            ShowPopup();
        }
      }
    </script>
    

    Then, bind the the OnClientClick event to the new script.

    <asp:Button ID="btn_Send" 
            runat="server" 
            ValidationGroup="SM" 
            Text="Send" 
            CausesValidation="true" 
            OnClientClick="ValidateAndShowPopup()"  />  
    

    By the way, the OnClick="Send_Click" event was shallowed by the behavior of the ModalPopupExtender's TargetControlID, So I removed it.