2011-04-28 86 views
1

我想在用戶嘗試更改DropDownList的選定項目時向用戶顯示確認對話框。如果選擇被確認,我想執行一些服務器端代碼。確認DropDownList選擇值

說,DDL具有值1和2。

  • 值1被選擇(默認)。
  • 用戶選擇值2.出現確認對話框。
  • 如果用戶選擇「是」,則所選項目將改變。一些服務器端代碼必須執行。
  • 如果用戶選擇「否」,則選定的項目將恢復爲值1.沒有執行服務器端代碼。

這個問題我有很多麻煩,因爲DDL有很少使用的事件。

到目前爲止,我得到了

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

和服務器端代碼SelectedIndexChanged事件的DDL的event handler

但我遇到了一個事實,即我既不能停止(或恢復)被更改的項目,也不會觸發該事件。

有什麼建議嗎?

回答

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"; 
+0

創造奇蹟!你今天讓某人開心:) – mcabral 2011-04-28 18:40:36

+0

太棒了!這正是我需要的。請確保在使用此項時關閉AutoPostBack = True,因爲else子句可爲您做到這一點。 – John 2012-01-11 22:55:22

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

注:設置的AutoPostBack Proerty假下拉列表中。