单击时按钮属性甚至不会触发

时间:2014-10-24 21:38:53

标签: c# onclick buttonclick

我使用下面的属性.Add方法来触发按钮事件,但它不会触发。

        if (String.IsNullOrEmpty(txt_DiscountCode.Text))
        {
            btn_Submit.Attributes.Add("onclick","return confirm('Do you want to continue without Discount Code?');");

        }

.aspx页面上的我的按钮是:

      <asp:Button ID="btn_Submit" runat="server" Text="Submit" OnClick="btn_Submit_Click" ValidationGroup="Submit1" />

相同的代码在GridView行命令下正常工作:

    protected void grid_EditUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Button btn_Update = (Button)(e.Row.Cells[7].FindControl("btn_Update"));
            Button btn_Delete = (Button)(e.Row.Cells[6].FindControl("btn_Delete"));
            if (btn_Update != null && btn_Update.Text == "Update")
            {
                btn_Update.Attributes.Add("onclick", "return confirm('Are you sure you want to save?');");
                //lnkbtn_Save.Attributes["onclick"] = "if(!confirm('Are you sure you want to save ?')){ return false; };";
            }
            else if (btn_Delete != null && btn_Delete.Text == "Delete")
            {
                btn_Delete.Attributes.Add("onclick", "return confirm('Are you sure you want to delete User?');");
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我猜您希望它会立即显示,但会在用户下次点击该按钮后显示。因此,您希望有条件地添加客户端事件处理程序。最简单的方法是始终添加它,但也要在客户端进行IsNullOrEmpty检查:

btn_Submit.Attributes.Add("onclick","var txt = document.getElementById('" + txt_DiscountCode.ClientID + "'); if(txt != null && txt.value == '') return confirm('Do you want to continue without Discount Code?');");