简体   繁体   English

c#onclick和onclientclick同时

[英]c# onclick and onclientclick at the same time

I have onclientclick and onclick events written for Exit button on my webpage. 我在我的网页上为“退出”按钮编写了onclientclick和onclick事件。 When clicked, it should first execute the update statement and then close the window. 单击时,应首先执行update语句,然后关闭窗口。

<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. Onclientclick正在解雇但不是onclick,即记录不会更新。 Is there a way to accomplish this? 有没有办法实现这个目标?

Thanks Rashmi 谢谢拉什米

OnClientClick is executed before the postback happens. 在回发发生之前执行OnClientClick It is usually used for things like client side validation where you need to prevent the postback from happening by using return false . 它通常用于客户端验证之类的事情,您需要使用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: 您需要删除OnClientClick属性,而是在服务器端处理程序中调用此行:

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. 这也意味着如果更新以异常结束,则窗口不会关闭。

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

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