如何在asp.net中使用chekboxchanged之前确认?

时间:2012-03-14 14:38:38

标签: c# javascript asp.net

我在gridview中使用checkbox控件我想在checkboxchanged事件之前显示确认。

确认框正在询问问题但不回发它,什么都不做......

// CS

        TemplateField field = new TemplateField(){
            HeaderText = "AKTIF",
            ItemTemplate = new AddTemplateToGridView("AKTIF")
        };
        field.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        field.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        field.ItemStyle.Width = Unit.Pixel(40);
        newXGrid.Columns.Add(field);

// ITEMPLATE

        public class AddTemplateToGridView : ITemplate
        {
            String columnName;

            public AddTemplateToGridView(String colname)
            {
                columnName = colname;
            }

            void ITemplate.InstantiateIn(System.Web.UI.Control container)
            {
                if (columnName == "AKTIF")
                {
                    CheckBox chk = new CheckBox() { ID="chkAktif", AutoPostBack=true };
                    chk.Attributes.Add("onclick","return confirm('Are you sure ?')");
                    chk.CheckedChanged += new EventHandler(l_CheckedChanged);
                    container.Controls.Add(chk);
                }
            }


            void l_CheckedChanged(object sender, EventArgs e)
            {
               ...
            }



        }

//我的复选框页面

<input id="ctl00_MainContent_ctl11_ctl02_chkAktif" type="checkbox" name="ctl00$MainContent$ctl11$ctl02$chkAktif" onclick="return confirm('Are you sure ?');setTimeout('__doPostBack(\'ctl00$MainContent$ctl11$ctl02$chkAktif\',\'\')', 0)">

2 个答案:

答案 0 :(得分:7)

改变这个:

chk.Attributes.Add("onclick","return confirm('Are you sure ?')");

到此:

chk.Attributes.Add("onclick","if (!confirm('Are you sure ?')) return false;");

为复选框设置AutoPostBack="true"以在点击时触发回发。

答案 1 :(得分:1)

您使用return with confirm对话框阻止javascript执行setTimeout()

试试这个:

if(confirm('Are you sure?'))
    setTimeout('__doPostBack(\'ctl00$MainContent$ctl11$ctl02$chkAktif\',\'\')', 0);
else
    return false;