简体   繁体   中英

c# onclick and onclientclick at the same time

I have onclientclick and onclick events written for Exit button on my webpage. When clicked, it should first execute the update statement and then close the window.

<asp:Button ID="ExitButton" runat="server"  OnClientClick="javaScript:self.close(); return false;" OnClick="ExitButton_Click"  UseSubmitBehavior="false" Text="Exit" Width="102px" CssClass="CssStyle2" Height="29px" />

protected void ExitButton_Click(object sender, EventArgs e)
{
    string sqlUpd = @"UPDATE top (2) [db1].[TestTable] set flag=0 
                     where Date is null and flag=-1";
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
    {
        connection.Open();
        SqlCommand cmdUpd = new SqlCommand(sqlUpd, connection);

        try
        {
            Int32 rows = cmdUpd.ExecuteNonQuery();
            connection.Close();
        }
        catch (Exception eupd)
        {
            lblUpdateErr.Text = "Error occurred in update";
        }
    }
}

Onclientclick is firing but not the onclick ie records are not updated. Is there a way to accomplish this?

Thanks Rashmi

OnClientClick is executed before the postback happens. It is usually used for things like client side validation where you need to prevent the postback from happening by using return false . Since you are always returning from your handler, the postback will never execute and thus the server side handler will not be called as well.

You need to remove the OnClientClick property and instead call this line in your server side handler:

ScriptManager.RegisterStartupScript(this, this.GetType(), "windowclose", "self.close();", true);

This will cause the window to be closed after the postback executes and the result is returned to the browser. This will also mean that if the update ends with an exception, the window is not closed.

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