确认DropDownList选择值
问题描述:
我想在用户尝试更改DropDownList的选定项目时向用户显示确认对话框。如果选择被确认,我想执行一些服务器端代码。确认DropDownList选择值
说,DDL具有值1和2。
- 值1被选择(默认)。
- 用户选择值2.出现确认对话框。
- 如果用户选择“是”,则所选项目将改变。一些服务器端代码必须执行。
- 如果用户选择“否”,则选定的项目将恢复为值1.没有执行服务器端代码。
这个问题我有很多麻烦,因为DDL有很少使用的事件。
到目前为止,我得到了
this.MyDropDown.Attributes["onChange"] = @"return confirm('Are you sure?');";
和服务器端代码SelectedIndexChanged
事件的DDL的event handler
。
但我遇到了一个事实,即我既不能停止(或恢复)被更改的项目,也不会触发该事件。
有什么建议吗?
答
它不触发服务器端事件的原因是因为您正在清除将触发回发的内置webforms事件处理程序。至于还原值,您需要保存并重新加载它。
添加此javascript函数
function handleChange(opt) {
if (!confirm('are you sure')) {
opt.selectedIndex = opt.oldIndex;
}
else {
__doPostBack('MyDropDown','')
}
}
,并设置客户端事件,像这样
this.MyDropDown.Attributes["onChange"] = "handleChange(this)";
this.MyDropDown.Attributes["onFocus"] = "this.oldIndex = this.selectedIndex";
答
这是完整的解决方案,因为我已经使用过了。只是参考以下说明:
// Paste it in Aspx file
function handleChange(opt) {
if (!confirm('Are you sure?')) {
opt.selectedIndex = opt.oldIndex;
}
else {
__doPostBack('MyDropDown','')
}
}
在页面加载粘贴此事件外的IsPostBack:
this.MyDropDown.Attributes["onChange"] = "handleChange(this)";
this.MyDropDown.Attributes["onFocus"] = "this.oldIndex = this.selectedIndex";
注:设置的AutoPostBack Proerty假下拉列表中。
创造奇迹!你今天让某人开心:) – mcabral 2011-04-28 18:40:36
太棒了!这正是我需要的。请确保在使用此项时关闭AutoPostBack = True,因为else子句可为您做到这一点。 – John 2012-01-11 22:55:22