ASP.NET 的 DropDownList 經過轉譯後就是一個普通的 <select>,因此取值方式與原生 JavaScript 完全一樣:靠 selectedIndex 找到選中項,再讀它的 value 與 text。
<script type="text/javascript" language="javascript">
function SearchChange() {
var ddl = document.getElementById("DropDownList1");
var index = ddl.selectedIndex;
var Value = ddl.options[index].value;
var Text = ddl.options[index].text;
alert(Value);
}
</script>
<asp:DropDownList ID="DropDownList1" runat="server" onchange="SearchChange();">
<asp:ListItem Value="0">111</asp:ListItem>
<asp:ListItem Value="1">222</asp:ListItem>
<asp:ListItem Value="2">333</asp:ListItem>
</asp:DropDownList>
這裡有兩個容易忽略的細節。ClientIDMode:ASP.NET 在命名容器中會自動改寫控制項的 client id(例如變成 ctl00_ContentPlaceHolder1_DropDownList1),此時 getElementById("DropDownList1") 就會找不到元素。若使用 .NET 4.0 以上,可將 ClientIDMode 設為 Static 保持 id 不變,或改用 <%= DropDownList1.ClientID %> 動態取值。
onchange 未必會觸發:<asp:DropDownList> 若沒有設定 AutoPostBack="true",變更選擇時通常不會引發任何事件;而設了 AutoPostBack 又會導致整頁回傳,客戶端的 onchange 行為依 .NET 版本而異。較可靠的做法是用 jQuery 在 document.ready 中綁定事件。
<script type="text/javascript">
$(document).ready(function () {
$("#<%= DropDownList1.ClientID %>").change(function () {
var value = $(this).val(); // 選中項的值
var text = $(this).find("option:selected").text(); // 選中項的文字
alert("值:" + value + ",文字:" + text);
});
});
</script>
用 <%= ... .ClientID %> 讓伺服器端把實際的 id 寫進客戶端程式碼,就不必操心命名容器改寫 id 的問題,這是在 Web Forms 中寫 JavaScript 最穩妥的做法。
string value = DropDownList1.SelectedValue;
string text = DropDownList1.SelectedItem.Text;
int index = DropDownList1.SelectedIndex;
取出後要使用,別忘了將 DropDownList 的 AutoPostBack 設為 true,或在表單提交後於 Page_Load 中處理。