确认DropDownList选择的值

时间:2011-04-28 17:27:44

标签: asp.net drop-down-menu

我想在用户尝试更改DropDownList的选定项时向用户显示确认对话框。如果确认选择,我想执行一些服务器端代码。

说,DDL的值为1和2.

  • 选择值1(默认值)。
  • 用户选择值2.将出现确认对话框。
  • 如果用户选择“是”,则所选项目会更改。必须执行某些服务器端代码。
  • 如果用户选择“否”,则所选项目将恢复为值1.没有执行服务器端代码。

我遇到这个问题很多,因为DDL几乎没有什么事情可以使用。

到目前为止我得到了

this.MyDropDown.Attributes["onChange"] = @"return confirm('Are you sure?');";

event handler用于服务器端代码的DDL的SelectedIndexChanged事件。

但我遇到的问题是,我既不能停止(或还原)正在更改的项目,也不能解雇SelectedIndexChanged事件。

有什么建议吗?

2 个答案:

答案 0 :(得分:4)

它没有触发服务器端事件的原因是因为你正在消除会触发回发的内置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";

答案 1 :(得分:0)

这是完整的解决方案,因为我已经使用过它。请参阅以下说明:

// 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";

注意:设置Dropdownlist的AutoPostBack Proerty False。