c# onclick and onclientclick at the same time

て烟熏妆下的殇ゞ 提交于 2021-02-11 17:48:06

问题


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 i.e. records are not updated. Is there a way to accomplish this?

Thanks Rashmi


回答1:


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.



来源:https://stackoverflow.com/questions/21550410/c-sharp-onclick-and-onclientclick-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!