How to Add Option Groups in ASP.NET Drop Down List

How can I add option groups in ASP.NET drop down list?

Check out this article, I too had need for Group DropDown list . . .

ASP.NET DropDownList with OptionGroup support

Usage :

protected void Page_Load(object sender, EventArgs e) 
{

ListItem item1 = new ListItem("Camel", "1");
item1.Attributes["OptionGroup"] = "Mammals";

ListItem item2 = new ListItem("Lion", "2");
item2.Attributes["OptionGroup"] = "Mammals";

ListItem item3 = new ListItem("Whale", "3");
item3.Attributes["OptionGroup"] = "Mammals";

ListItem item4 = new ListItem("Walrus", "4");
item4.Attributes["OptionGroup"] = "Mammals";

ListItem item5 = new ListItem("Velociraptor", "5");
item5.Attributes["OptionGroup"] = "Dinosaurs";

ListItem item6 = new ListItem("Allosaurus", "6");
item6.Attributes["OptionGroup"] = "Dinosaurs";

ListItem item7 = new ListItem("Triceratops", "7");
item7.Attributes["OptionGroup"] = "Dinosaurs";

ListItem item8 = new ListItem("Stegosaurus", "8");
item8.Attributes["OptionGroup"] = "Dinosaurs";

ListItem item9 = new ListItem("Tyrannosaurus", "9");
item9.Attributes["OptionGroup"] = "Dinosaurs";

ddlItems.Items.Add(item1);
ddlItems.Items.Add(item2);
ddlItems.Items.Add(item3);
ddlItems.Items.Add(item4);
ddlItems.Items.Add(item5);
ddlItems.Items.Add(item6);
ddlItems.Items.Add(item7);
ddlItems.Items.Add(item8);
ddlItems.Items.Add(item9);

}

Dropdownlist control with optgroups for asp.net (webforms)?

I've used the standard control in the past, and just added a simple ControlAdapter for it that would override the default behavior so it could render <optgroup>s in certain places. This works great even if you have controls that don't need the special behavior, because the additional feature doesn't get in the way.

Note that this was for a specific purpose and written in .Net 2.0, so it may not suit you as well, but it should at least give you a starting point. Also, you have to hook it up using a .browserfile in your project (see the end of the post for an example).

'This codes makes the dropdownlist control recognize items with "--"
'for the label or items with an OptionGroup attribute and render them
'as <optgroup> instead of <option>.
Public Class DropDownListAdapter
Inherits System.Web.UI.WebControls.Adapters.WebControlAdapter

Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
Dim list As DropDownList = Me.Control
Dim currentOptionGroup As String
Dim renderedOptionGroups As New Generic.List(Of String)

For Each item As ListItem In list.Items
Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value)
If item.Attributes("OptionGroup") IsNot Nothing Then
'The item is part of an option group
currentOptionGroup = item.Attributes("OptionGroup")
If Not renderedOptionGroups.Contains(currentOptionGroup) Then
'the header was not written- do that first
'TODO: make this stack-based, so the same option group can be used more than once in longer select element (check the most-recent stack item instead of anything in the list)
If (renderedOptionGroups.Count > 0) Then
RenderOptionGroupEndTag(writer) 'need to close previous group
End If
RenderOptionGroupBeginTag(currentOptionGroup, writer)
renderedOptionGroups.Add(currentOptionGroup)
End If
RenderListItem(item, writer)
ElseIf item.Text = "--" Then 'simple separator
RenderOptionGroupBeginTag("--", writer)
RenderOptionGroupEndTag(writer)
Else
'default behavior: render the list item as normal
RenderListItem(item, writer)
End If
Next item

If renderedOptionGroups.Count > 0 Then
RenderOptionGroupEndTag(writer)
End If
End Sub

Private Sub RenderOptionGroupBeginTag(ByVal name As String, ByVal writer As HtmlTextWriter)
writer.WriteBeginTag("optgroup")
writer.WriteAttribute("label", name)
writer.Write(HtmlTextWriter.TagRightChar)
writer.WriteLine()
End Sub

Private Sub RenderOptionGroupEndTag(ByVal writer As HtmlTextWriter)
writer.WriteEndTag("optgroup")
writer.WriteLine()
End Sub

Private Sub RenderListItem(ByVal item As ListItem, ByVal writer As HtmlTextWriter)
writer.WriteBeginTag("option")
writer.WriteAttribute("value", item.Value, True)
If item.Selected Then
writer.WriteAttribute("selected", "selected", False)
End If

For Each key As String In item.Attributes.Keys
writer.WriteAttribute(key, item.Attributes(key))
Next key

writer.Write(HtmlTextWriter.TagRightChar)
HttpUtility.HtmlEncode(item.Text, writer)
writer.WriteEndTag("option")
writer.WriteLine()
End Sub
End Class

Here's a C# implementation of the same Class:

/* This codes makes the dropdownlist control recognize items with "--"
* for the label or items with an OptionGroup attribute and render them
* as <optgroup> instead of <option>.
*/
public class DropDownListAdapter : WebControlAdapter
{
protected override void RenderContents(HtmlTextWriter writer)
{
//System.Web.HttpContext.Current.Response.Write("here");
var list = (DropDownList)this.Control;
string currentOptionGroup;
var renderedOptionGroups = new List<string>();

foreach (ListItem item in list.Items)
{
Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value);
//Is the item part of an option group?
if (item.Attributes["OptionGroup"] != null)
{
currentOptionGroup = item.Attributes["OptionGroup"];
//Was the option header already written, then just render the list item
if (renderedOptionGroups.Contains(currentOptionGroup))
RenderListItem(item, writer);
//The header was not written,do that first
else
{
//Close previous group
if (renderedOptionGroups.Count > 0)
RenderOptionGroupEndTag(writer);

RenderOptionGroupBeginTag(currentOptionGroup, writer);
renderedOptionGroups.Add(currentOptionGroup);
RenderListItem(item, writer);
}
}
//Simple separator
else if (item.Text == "--")
{
RenderOptionGroupBeginTag("--", writer);
RenderOptionGroupEndTag(writer);
}
//Default behavior, render the list item as normal
else
RenderListItem(item, writer);
}

if (renderedOptionGroups.Count > 0)
RenderOptionGroupEndTag(writer);
}

private void RenderOptionGroupBeginTag(string name, HtmlTextWriter writer)
{
writer.WriteBeginTag("optgroup");
writer.WriteAttribute("label", name);
writer.Write(HtmlTextWriter.TagRightChar);
writer.WriteLine();
}
private void RenderOptionGroupEndTag(HtmlTextWriter writer)
{
writer.WriteEndTag("optgroup");
writer.WriteLine();
}
private void RenderListItem(ListItem item, HtmlTextWriter writer)
{
writer.WriteBeginTag("option");
writer.WriteAttribute("value", item.Value, true);
if (item.Selected)
writer.WriteAttribute("selected", "selected", false);

foreach (string key in item.Attributes.Keys)
writer.WriteAttribute(key, item.Attributes[key]);

writer.Write(HtmlTextWriter.TagRightChar);
HttpUtility.HtmlEncode(item.Text, writer);
writer.WriteEndTag("option");
writer.WriteLine();
}
}

My browser file was named "App_Browsers\BrowserFile.browser" and looked like this:

<!--
You can find existing browser definitions at
<windir>\Microsoft.NET\Framework\<ver>\CONFIG\Browsers
-->
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.DropDownList"
adapterType="DropDownListAdapter" />
</controlAdapters>
</browser>
</browsers>

Support for optgroup in dropdownlist .NET MVC?

Looking through the code on www.codeplex.com/aspnet, it doesn't appear that neither the SelectList nor the DropDownList extension method supports the use of OptGroup in a select. Looks like you'll need to write your own extension method and extend SelectListItem to contain the grouping or generate the select manually in markup.

Dropdownlist with optgroup using WebControlAdapters

I solved the issue.
The problem was in the method LoadDDLModelli.
Instead of setting DataSource and do the DataBind to the Dropdownlist passed via reference, I have to add ItemList singoularly (I cannot understand the difference)

public static void loadDDLModelli(ref DropDownList ddl, List<dynamic> objects)
{
Int16 cont = 0;
ddl.Items.Clear();
System.Web.UI.WebControls.ListItem li;
String idModello = "";
String nomeModello = "";
String nomeBrand = "";
String oggetto = "";

List<System.Web.UI.WebControls.ListItem> items = new List<System.Web.UI.WebControls.ListItem>();
foreach (var item in objects)
{
oggetto = item.ToString().Replace("{", "").Replace("}", "");
idModello = oggetto.Split(',')[0].Split('=')[1].Trim();
nomeModello = oggetto.Split(',')[1].Split('=')[1].Trim();
nomeBrand = oggetto.Split(',')[2].Split('=')[1].Trim();
li = new System.Web.UI.WebControls.ListItem(nomeBrand+" - "+nomeModello, idModello);
li.Attributes["Group"] = nomeBrand;
items.Add(li);
cont++;
};

//ddl.DataSource = items;
//ddl.DataBind();

foreach(ListItem i in items)
ddl.Items.Add(i);

ddl.SelectedIndex = -1;
}

Constructing a Select List with OptGroup groups

Firstly, you view model should not contain database access code to populate its properties. That is the responsibility of the controller and you have made your code impossible to unit test. Start by changing the model to

public class CreateClientViewModel
{
[DisplayName("City")]
public string CityId { get; set; }
public IList<SelectListItem> CityList { get; set; }
....
}

Then in the controller, you can use one of the overloads of SelectList that accepts a groupName to generate the collection

var cities = var cities = db.City.Include(x => x.Region).Where(x => x.Active == true)
.OrderBy(x => x.Region.RegionName).ThenBy(x => x.CityName);

var model = new CreateClientViewModel()
{
CityList = new SelectList(cities, "CityId", "CityName", "Region.RegionName", null, null)
};
return View(model);

And in the view

@Html.DropDownListFor(x => x.CityId, Model.CityList , "« ‹ Select › »", new { @class = "form-control" })

As an alternative, you can also do this using the Group property of SelectListItem

var model = new CreateClientViewModel()
{
CityList = new List<SelectListItem> // or initialize this in the constructor
};
var cities = var cities = db.City.Include(x => x.Region).Where(x => x.Active == true).GroupBy(x => x.Region.RegionName);
foreach(var regionGroup in cities)
{
var optionGroup = new SelectListGroup() { Name = regionGroup.Key };
foreach(var city in regionGroup)
{
model.CityList.Add(new SelectListItem() { Value = city.CityId.ToString(), Text = city.CityName, Group = optionGroup });
}
}
return View(model);

ASP.Net MVC 3: optgroup support in Html.DropDownListFor

How can i make my DropDownListFor support optgroup?

There is no built-in support in the framework for this kind of drop down lists. You will have to write your own custom helper or generate the HTML manually (I would tend towards the first option).

How do I populate a dropdown list with members of an Active Directory Group in ASP.NET Core?

In your razor page , change to use below code :

<select id="manager" class="form-control form-control-sm" asp-items="@((List<SelectListItem>)IndexModel.ManagementUsers)">
<option value=""></option>
</select>

As @poke suggested , you can directly use asp-items="@IndexModel.ManagementUsers"



Related Topics



Leave a reply



Submit