Get the value of a dropdown with Bootstrap optgroup in ASP.NET

2

Does anyone know how to get the values of a dropdown of Bootstrap with optgroup in ASP.NET ? I attach a reference image If I put the dropdown attribute: runat="server" , to have it in the backend, I get the error of the image. It seems that asp.net does not accept that an html select has optgroup

    
asked by Jeremy 22.01.2016 в 23:52
source

2 answers

2

I do not think I have a direct mapping of this type of control to one of asp.net, so the runet="server" does not apply

You should evaluate using jquery, by $.ajax , you could invoke WebMethod in the aspx page, in this case the data would be taken with client code and sent to the server, there is no postback or events.

Using jQuery to directly call ASP.NET AJAX page methods

Calling ASP.Net WebMethod using jQuery AJAX

Where I point out is that if you are going to use boostrap you should evaluate to stop using asp.net concepts, especially events, they do not get anything right.

    
answered by 23.01.2016 в 00:34
0

When you put an <select> element, you put the runat="server" attribute on the WebControl HtmlSelect that does not support optgroup .

To get access to the selected option from the server, you have two options

Option 1: Element pure HTML select and the selected value access through Request.Form . The drawback of this option is that it remains a pretty ugly code (especially to set the selected item from server)

HTML Code:

<select name="CarField">
<option value="">-Seleccione una opción-</option>
<optgroup label="Swedish Cars">
    <option value="volvo" <%=SelectedCar == "volvo" ? "selected" : ""%>>Volvo</option>
    <option value="saab" <%=SelectedCar == "saab" ? "selected" : ""%>>Saab</option>
</optgroup>
<optgroup label="German Cars">
    <option value="mercedes" <%=SelectedCar == "mercedes" ? "selected" : ""%>>Mercedes</option>
    <option value="audi" <%=SelectedCar == "audi" ? "selected" : ""%>>Audi</option>
</optgroup>

Code C #

public partial class _Default : Page 
{
   protected string SelectedCar { get; set; }

   protected void Page_Load(object sender, EventArgs e)
   {
       SelectedCar = Request.Form["CarField"];

       Label1.Text = $"El coche seleccionado es: {SelectedCar}";
   }
}

Option 2 : Implement a WebControl. In this article (in English) " ADDING GROUPS TO THE ASP.NET DROPDOWNLIST CONTROL "You have an example of implementation. This would be the recommended option, especially to have a cleaner and reusable code.

    
answered by 24.01.2016 в 19:53