简体   繁体   中英

Call javascript in between a button OnClick event in C#

I have a button with OnClick event on my web page.

<asp:TextBox ID="tbMailID" runat="server" Width="250px"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />

C# code:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    bool IsGmail = CheckMailId(tbMailID.Text);
    if(!IsGmail)
    {
        string strScript = "confirm('Mail id is not from gmail, do you still want to continue?');";
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "strScript", strScript, true);
    }
    SendMail(); 
}

The page accepts a mail id in textbox and on submit sends a mail. But if mail-id is not an gmail id (validated by CheckMailId) i want to show a confirmation box to user whether he/she wants to get a mail, based on the Yes/No clicked.

But the javascript will get call after the submit event is served and mail is sent. if i add a return SendMail() will never get calls

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "strScript", strScript, true);
return;

What could be a possible solution here?

Note: the code posted is simplified version of my real use case. CheckMailId - is just a name to show, it calls up many other functions and do few db process. So incorporating that in javascript, i would like to avoid.

You can call a script befroe event lke this:-

            <script type="text/javascript">
    function Confirm() {
       var yourstring = document.getElementById('<%= tbMailID.ClientID %>').value;
       if (/@gmail\.com$/.test(yourstring)) {
             return true;
               }
             else
              {
        if (confirm("Mail id is not from gmail, do you still want to continue?") == true)
            return true;
        else
            return false;
    }
       }
</script>

strong text

       <asp:Button ID="btnSubmit" runat="server" OnClientClick="return Confirm();" OnClick="btnSubmit_Click" Text="Submit" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM