在网页制作中经常出现是否确认按钮,特别是在删除数据库是,如果没有做这种设置就会引起数据的丢失。如果做了确认按钮后就会给用户一次补救的机会,这样就避免了不必要的数据丢失。如果直接用js写的话有很难和后台的操作联系。
解决方案:
给按钮添加Attributes属性,即Button1.Attributes["OnClick"] = "return confirm('are you sure?')";
这样在客户端生成 OnClick="return confirm('are you sure?')" 用户执行按钮的操作时,先在本地执行弹出一个confirm的确认窗口,再根据用户的选择,判断是否要执行按钮的操作。可能在刚开始的时候会认为服务器端是怎么知道用户的选择,其实在点击后,当选择“取消”时客户端自己进行确认,并没有发到服务器端进行确认。
下面就是一个例子
.aspx代码





.cs代码













其实在asp.net用到确认按钮最多的是后台的删除操作。一般在datagrid上用的比较多。
在datagrid的操作就是多按钮项的操作。所以首先要做的事情就是找到按钮项,在把confirm绑上去。
private void infolist_ItemDataBound(object sender, DataGridItemEventArgs e){ if(e.Item.ItemType!=ListItemType.Header&& .Item.ItemType!=ListItemType.Footer)
{
LinkButton deleteButton = (LinkButton) e.Item.Cells[4].Controls[0];
deleteButton.Attributes["OnClick"]="return confirm('你确认要删除吗?')";
}
}
在项绑定函数ItemDataBound中先排除顶和底,因为那里是没有我们要找的按钮的。在找到我们要找的按钮将OnClick绑到按钮中就可以了