2010-03-04 65 views
29

選擇我有下面的代碼:如何獲得選擇一個HTML的值與asp.net

<select id="testSelect"> 
    <option value="1">One</option> 
    <option value="2">Two</option> 
</select> 
<asp:Button ID="btnTest" runat="server" Text="Test it!" onclick="btnTest_Click" /> 

我需要選擇的選項上回發值。我怎樣才能做到這一點與asp.net?

+1

好...多值如何? – 2010-04-02 16:47:29

回答

39

你需要一個名字添加到您的<select>元素:

<select id="testSelect" name="testSelect"> 

將發佈到服務器,你可以使用看出來:

Request.Form["testSelect"] 
+0

非常感謝。 – 2010-03-04 10:16:23

+1

沒問題。如果可能的話,Pontus就使用服務器端下拉提出了一個有效的觀點,但我認爲你有一個很好的理由不使用它。 – Kobi 2010-03-04 10:19:36

+0

用戶選擇多個值的運氣? – 2010-04-02 16:47:52

1

的Java腳本:

使用elementid. selectedIndex()函數得到所選索引

6

如果您使用asp:dropdownlist,您可以通過testSelect.Text更容易地選擇它。

現在,您必須按Request.Form["testSelect"]才能獲得按btnTes後的值。

希望它有幫助。

編輯:您需要指定選擇(不僅是ID)的name到能夠從微軟Request.Form["testSelect"]

0
<%@ Page Language="C#" AutoEventWireup="True" %> 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml">  
<head> 
    <title> HtmlSelect Example </title> 
    <script runat="server"> 
     void Button_Click (Object sender, EventArgs e) 
     { 
     Label1.Text = "Selected index: " + Select1.SelectedIndex.ToString() 
         + ", value: " + Select1.Value;  
     }  
    </script>  
</head>  
<body>  
    <form id="form1" runat="server"> 

     Select an item: 

     <select id="Select1" runat="server">  
     <option value="Text for Item 1" selected="selected"> Item 1 </option> 
     <option value="Text for Item 2"> Item 2 </option> 
     <option value="Text for Item 3"> Item 3 </option> 
     <option value="Text for Item 4"> Item 4 </option> 
     </select> 

     <button onserverclick="Button_Click" runat="server" Text="Submit"/> 

     <asp:Label id="Label1" runat="server"/>  
    </form> 
</body> 
</html> 

來源。希望這有幫助!

+1

你在我的代碼中看到runat服務器指令嗎? – 2014-04-04 19:13:15

4

我已經使用這個解決方案來得到你需要的東西。

Let'say,在我的.aspx代碼有一個選擇列表RUNAT =「服務器」:

<select id="testSelect" runat="server" ClientIDMode="Static" required> 
    <option value="1">One</option> 
    <option value="2">Two</option> 
</select> 

在我用下面的代碼來檢索文本,也值的選項我的C#代碼:

testSelect.SelectedIndex == 0 ? "uninformed" : 
    testSelect.Items[testSelect.SelectedIndex].Text); 

在這種情況下,我檢查用戶是否選擇了任何選項。如果沒有選中任何內容,我會將文本顯示爲「不知情」。

+0

正如您所看到的,問題是關於沒有runat服務器屬性的select。 – 2015-07-20 14:15:58

+0

是的,我知道,我只是爲了達到同樣的結果而另闢蹊徑。感謝評論=) – 2015-07-20 14:27:21