简体   繁体   中英

OnClick executes after OnClientClick in asp.net

I have an asp button that executes a javascript function using OnClientClick, I also want to execute OnClick after OnClientClick, however, it never executes. I have gone through a lot of the same topics on StackOverflow and other pages but it seems not to work for me.

<asp:Button ID="btn_del" runat="server" Font-Bold="True" Text="DELETE" Width="130px" UseSubmitBehavior="false" OnClientClick="if (!RunDelete()) return false;" OnClick="btn_del_Click" />

function RunDelete() {
        OnDelete("Delete?", function yes() {
            var id = $('#<%=txt_id.ClientID%>').val();

            $.ajax({
                type: "POST",
                url: "/demo.aspx/DeleteRowDb",
                data: JSON.stringify({ "RecordID": id }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(response.d);
                }
            });
            return true;
            
        },
            function no() {
                return false;
            });
    }

I also try to create another button with the same OnClick and try to execute from javascript using document.getElementById('<%= btn_del2.ClientID %>').click();but still it does not work. I need to execute the OnClick because I need the protected void in the code behind to work meanwhile I cannot do much in the public static string function.

Ok, lets break this down a bit.

First, no need (or reason) to have submit behavour = false.

We have a plain jane button here.

So, say this:

        <asp:Button ID="btn_del" runat="server" 
            Font-Bold="True" Text="DELETE" Width="130px" 
            OnClick="btn_del_Click" />

Ok, when we click on above, our code behind runs.

say this for now:

    protected void btn_del_Click(object sender, EventArgs e)
    {
        Debug.Print("Code to delete follows");
    }

Ok, above works.

Now, to control if this button (code behind) runs our code, then we can introduce a OnClientClick.

And if that client side (JavaScript) returns true, then the code behind runs, and if we return false, then the button code does not run.

So, we now can have this:

        <asp:Button ID="btn_del" runat="server" 
            Font-Bold="True" Text="DELETE" Width="130px" 
            OnClick="btn_del_Click"
            OnClientClick="return myprompt()"
            CssClass="btn" />

        <script>
            function myprompt() {
                return confirm("Really delete this?")
            }
        </script>

And now we have this result:

在此处输入图像描述

So, if the user hits ok, then code behind will run.

If user hits Cancel, then code behind will not run.

So, the above is the basic design, and approach here.

Ok, the built in browser dialog tends to not look that great.

So, then lets do this with say one of the many (boatloads) of dialog helpers and add-ins we might want to use.

Since every web site, even these webforms web site has jQuery included by default, then a really great dialog add-in is to use jQuery.ui.

Assuming jQuery.UI, then such code has to be changed a bit.

The way jQuery (and most dialog add-ins) work is you create a div, and inside is your content for the prompt.

However, and this is BEYOND important:

Most (if not all) 3rd party dialog widgets don't block calling code.

In other words, using js alert('some message'), or confirm('some message') are VERY easy, because they HALT the calling code.

However, most (if not all) js code these days does NOT block, or HALT calling code. This is to not freeze up the browser, so near ALL browser code these days is what we call asynchronous. The code will NOT wait.

So, lets do this with a nice dialog, and lets place the dialog right next to the button click.

So, using jQuery.UI (I do recommend), then our code becomes this:

        <asp:Button ID="btn_del" runat="server" 
            Font-Bold="True" Text="DELETE" Width="130px" 
            OnClick="btn_del_Click"
            OnClientClick="return myprompt(this)"
            CssClass="btn" />

        <script>
            mypromptok = false
            function myprompt(btn) {
                if (mypromptok) {
                    return true
                }
                // lets pop jquery.UI dialog
                var mydiv = $("#mydeldiv")
                mydiv.dialog({
                    modal: true,
                    appendTo: "form",
                    title: "Delete Hotel?",
                    closeText: "",
                    width: "400px",
                    position: { my: 'left top', at: 'right bottom', of: btn },
                    buttons: {
                        ' ok ': function () {
                            mypromptok = true
                            btn.click() // click button again
                        },
                        ' cancel ': function () {
                            mydiv.dialog('close')
                        }
                    }
                });
                return false
            }
        </script>

        <div id="mydeldiv" style="display:none">
            <h3><i>Delete this Hotel</i></h3>
            <h4><i>This cannot be un-done</i></h4>
        </div>

The results are nice, since the pop is dialog, it fades out (gray's out the back ground), and the dialog is positioned RIGHT where the user just clicked (their eye's focus it on that button, so popping the dialog right below and to the right of the button is where the user was/is looking anyway).

Ok, so now, lets take the above knowledge, and use this from say a grid of rows, and now have a delete button, and our prompt.

Note you can use the super simple confirm() dialog, as per first example, or fancy 2nd example.

So, lets assume a gridview, and a button to delete the data.

So, say this markup:

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataKeyNames="ID" CssClass="table table-hover" Width="40%">
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="LastName" />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName" />
                <asp:BoundField DataField="City" HeaderText="City" />
                <asp:BoundField DataField="Description" HeaderText="Description" />
                <asp:TemplateField HeaderText="" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                    <asp:Button ID="btn_del" runat="server" 
                        Font-Bold="True" Text="Delete" 
                        OnClick="btn_del_Click"
                        OnClientClick="return myprompt(this)"
                        CssClass="btn" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

Note our button in above.

So, code to load grid is say this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();

    }

    void LoadGrid()
    {
        string strSQL = @"SELECT * FROM tblHotelsA ORDER BY HotelName";
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                conn.Open();
                DataTable rstData = new DataTable();
                rstData.Load(cmdSQL.ExecuteReader());
                GridView1.DataSource = rstData;
                GridView1.DataBind();
            }
        }            
    }

And now we have this:

在此处输入图像描述

And clicking on our button, we see this:

在此处输入图像描述

so, now our delete code for that button will be this:

    protected void btn_del_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        GridViewRow gRow = (GridViewRow)btn.NamingContainer;

        // get database PK id of row click
        int pkID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];

        string strSQL = "DELETE FROM tblHotelsA WHERE ID = @ID";
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                cmdSQL.Parameters.Add("@ID", SqlDbType.Int).Value = pkID;
                conn.Open();
                cmdSQL.ExecuteNonQuery();
            }
        }
    }

So, again, we have a simple code event (code behind), and we conditional run this code based on the client side confirm() (built in js dialog), or the last example, in which we used a jQuery.UI dialog.

So, if you want to use the 2nd example (jQuery.UI), then you WILL HAVE to add/install jQuery.UI to your project.

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