How to get selected value of a html select with asp.net

后端 未结 5 536
死守一世寂寞
死守一世寂寞 2020-12-16 09:36

I have code below:


                        
    
提交评论

  • 2020-12-16 10:06
    <%@ 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>
    

    Source from Microsoft. Hope this is helpful!

    0 讨论(0)
  • 2020-12-16 10:11

    You need to add a name to your <select> element:

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

    It will be posted to the server, and you can see it using:

    Request.Form["testSelect"]
    
    0 讨论(0)
  • 2020-12-16 10:15

    Java script:

    use elementid. selectedIndex() function to get the selected index

    0 讨论(0)
  • 2020-12-16 10:19

    If you would use asp:dropdownlist you could select it easier by testSelect.Text.

    Now you'd have to do a Request.Form["testSelect"] to get the value after pressed btnTes.

    Hope it helps.

    EDIT: You need to specify a name of the select (not only ID) to be able to Request.Form["testSelect"]

    0 讨论(0)
  • 提交回复
    热议问题