开发者

How do I get the value of a select in code-behind?

I am using ASP.NET and in my .aspx page I have the following code, and, based on the selection, I am displaying the appropriate divs. It's working great, as is, but the question is: How do I get the value (whatever selected by user) on code-behind?

<select id="filterResultsBy"  >
    <option value="">Select...</option>
    <option value="Date">Date</option>
    <option value="Subject">Subject</option> 
    <option value="Status">Status</option>
</select>

If I add runat="server" or use the serv开发者_如何转开发er asp:DropDownList control, jQuery does not work.

$('#ddlFilter').change(function(){ 
   var sel = $(this).val(); 
   if(sel === 'DATE'){ 
     hideAll();// a function to hide all the divs first 
     $('#divDateRangeSearch').show(); 
   } else if(sel === 'SUBJECT'){ 
     ///so on... 
   } 
}); 


In ASP.NET the usual convention is to use server side controls which work better with the Postback model. So you could use the equivalent:

<asp:DropDownList ID="filterResultsBy" runat="server" CssClass="ddlFilter">
    <asp:ListItem Value="" Text="Select..." />
    <asp:ListItem Value="Date" Text="Date" />
    <asp:ListItem Value="Subject" Text="Subject" />
    <asp:ListItem Value="Status" Text="Status" />
</asp:DropDownList>

which would allow you to access the filterResultsBy variable in the code behind and retrieve the currently selected value. To make this work with client scripting libraries such as jQuery add a class and use a class selector instead of id selector because of the name mangling that occurs in ASP.NET server side controls:

$('.ddlFilter').change(function() {
    var sel = $(this).val(); 
    if(sel === 'DATE') { 
        hideAll(); // a function to hide all the divs first 
        $('#divDateRangeSearch').show(); 
    } else if (sel === 'SUBJECT') { 
        ///so on... 
    } 
});


You need to add RunAt="Server" to your select tag.

<select id="filterResultsBy" Runat="Server"  >
     <option value="">Select...</option>
     <option value="Date">Date</option>
     <option value="Subject">Subject</option> 
     <option value="Status">Status</option>
</select>


Either use a DropDownList control or add the runat="server" attribute to the select tag to upgrade it to a HtmlSelect control.


another option (if you're looking to ajaxify your page) would be to keep your select as-is and just use a jquery ajax call to communicate via web/page methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜