Reputation: 908
How can I add a server event for an HTML Select control?
HTML code is like this:
<div class="ui-widget">
<select id="Select1" runat="server">
<option>Select one...</option>
<option>ActionScript</option>
<option>AppleScript</option>
<option>Asp</option>
<option>BASIC</option>
</select>
</div>
C# code is like this:
public void Select1_SomethingChange(object sender, EventArgs e)
{
//random code
}
Now I know just as is it won't work, the 2nd line of the HTML needs an attribute of some kind.. I already tried the only 2 I could find which are these two below
<select id="Select1" runat="server" onServerChanged="Select1_SomethingChange">
<select id="Select1" runat="server" onSelectedIndexChanged="Select1_SomethingChange">
The problem is that the first options event never fires, and the 2nd option just doesn't exist. Please help me out here, any help is welcome.
Upvotes: 1
Views: 6696
Reputation: 5232
The 2013 answer is pretty conservative. The select
element has the OnChange
event, see: this MS doc
The event handler in code-behind is only called after a post event. For Asp controls, you add the AutoPostBack
attribute, otherwise you just call the __doPostBack()
javascript method.
Complete example:
<select id="select_clients" runat="server"
OnServerChange="SelectClients_Change" onchange="__doPostBack()">
</select>
code-behind:
using System.Web.UI.HtmlControls;//HtmlSelect
protected void SelectClients_Change(object sender, EventArgs e)
{
HtmlSelect HS = sender as HtmlSelect;
ListItem SelectedItem = HS.Items[HS.SelectedIndex];
}
NB: the options I added dynamically in Page_Load using:
select_clients.Items.Add(new ListItem("...name...", "...value...")
Why use the primitive html elements and __doPostBack call instead of the higher level Asp.Net controls? Well, sometimes this is convenient, e.g. in combination with the Bootstrap framework.
Upvotes: 1
Reputation: 219016
When you add runat="server"
to an otherwise normal HTML element, it becomes an HtmlControl
in the server-side code. Which doesn't expose a lot of events. In order to get richer server-side eventing, you need to use the ASP.NET controls. In this case that would be a DropDownList
, which has the events you're looking for.
Something like this:
<div class="ui-widget">
<asp:DropDownList id="Select1" OnSelectedIndexChanged="Select1_SomethingChange" runat="server">
<asp:ListItem Selected="True" Value="White"> White </asp:ListItem>
<asp:ListItem Value="Select one...">Select one...</asp:ListItem>
<asp:ListItem Value="ActionScript">ActionScript</asp:ListItem>
<asp:ListItem Value="AppleScript">AppleScript</asp:ListItem>
<asp:ListItem Value="Asp">Asp</asp:ListItem>
<asp:ListItem Value="BASIC">BASIC</asp:ListItem>
</asp:DropDownList>
</div>
Upvotes: 0