简体   繁体   English

在C#中的按钮OnClick事件之间调用javascript

[英]Call javascript in between a button OnClick event in C#

I have a button with OnClick event on my web page. 我的网页上有一个带有OnClick事件的按钮。

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

C# code: C#代码:

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. 该页面在文本框中接受邮件ID,并在提交时发送邮件。 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. 但是,如果mail-id不是gmail id(由CheckMailId验证),则我想根据是/否单击向用户显示一个确认框,以确认他/她是否要接收邮件。

But the javascript will get call after the submit event is served and mail is sent. 但是javascript会在提供Submit事件并发送邮件后得到调用。 if i add a return SendMail() will never get calls 如果我添加一个返回SendMail()将永远不会收到电话

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. CheckMailId-只是要显示的名称,它调用了许多其他功能,并且很少执行数据库进程。 So incorporating that in javascript, i would like to avoid. 因此,将其合并到javascript中,我想避免。

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" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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