I have a requirement of grouping the drop down list options in ASP.NET drop down server control. Do you have any idea to how to approach the issue? I am new to ASP.NET.
我需要对ASP中的下拉列表选项进行分组。NET下拉服务器控件。你知道怎么处理这个问题吗?我对ASP.NET是新手。
9 个解决方案
#1
35
Check out this article, I too had need for Group DropDown list . . .
看看这篇文章,我也需要组下拉列表…
ASP.NET DropDownList with OptionGroup support
ASP。NET下拉列表与OptionGroup支持
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);
}
#2
31
I really like this client-side solution (doesn't need a custom DropDownList, but uses jQuery):
我非常喜欢这个客户端解决方案(不需要自定义的DropDownList,但使用jQuery):
backend
后端
private void _addSelectItem(DropDownList list, string title, string value, string group = null) {
ListItem item = new ListItem(title, value);
if (!String.IsNullOrEmpty(group))
{
item.Attributes["data-category"] = group;
}
list.Items.Add(item);
}
...
_addSelectItem(dropDown, "Option 1", "1");
_addSelectItem(dropDown, "Option 2", "2", "Category");
_addSelectItem(dropDown, "Option 3", "3", "Category");
...
client
客户端
var groups = {};
$("select option[data-category]").each(function () {
groups[$.trim($(this).attr("data-category"))] = true;
});
$.each(groups, function (c) {
$("select option[data-category='"+c+"']").wrapAll('<optgroup label="' + c + '">');
});
#3
4
This is old but since I used the accepted answer recently I wanted to share my experience with it. While it does provide the correct markup, it caused problems for me, specifically whenever I tried to submit a form with any dropdownlist I would get the dreaded "Invalid postback or callback argument" error. After googling like a maniac, I came across this article which then links to this blog post. The code I ended up using was this:
这是旧的,但由于我最近使用了公认的答案,我想与它分享我的经验。虽然它确实提供了正确的标记,但它给我带来了问题,特别是每当我试图提交带有任何下拉列表的表单时,我都会遇到可怕的“无效回发或回调参数”错误。在像疯子一样谷歌之后,我发现了这篇文章,然后链接到这篇博文。我最后使用的代码是:
public class DropDownListAdapter : System.Web.UI.WebControls.Adapters.WebControlAdapter {
protected override void RenderContents(HtmlTextWriter writer) {
var dropDownList = (DropDownList)Control;
var items = dropDownList.Items;
var groups = (from p in items.OfType<ListItem>()
group p by p.Attributes["Group"] into g
select new { Label = g.Key, Items = g.ToList() });
foreach (var group in groups)
{
if (!String.IsNullOrEmpty(group.Label))
{
writer.WriteBeginTag("optgroup");
writer.WriteAttribute("label", group.Label);
writer.Write(">");
}
var count = group.Items.Count();
if (count > 0)
{
var flag = false;
for (var i = 0; i < count; i++)
{
var item = group.Items[i];
writer.WriteBeginTag("option");
if (item.Selected)
{
if (flag)
{
throw new HttpException("Multiple selected items not allowed");
}
flag = true;
writer.WriteAttribute("selected", "selected");
}
if (!item.Enabled)
{
writer.WriteAttribute("disabled", "true");
}
writer.WriteAttribute("value", item.Value, true);
if (Page != null)
{
Page.ClientScript.RegisterForEventValidation(dropDownList.UniqueID, item.Value);
}
writer.Write('>');
HttpUtility.HtmlEncode(item.Text, writer);
writer.WriteEndTag("option");
writer.WriteLine();
}
}
if (!String.IsNullOrEmpty(group.Label))
{
writer.WriteEndTag("optgroup");
}
}
}
}
The listitems used here are created in the design page rather than the code-behind page like so:
这里使用的listitems是在设计页面中创建的,而不是像这样的代码隐藏页面:
<asp:ListItem Value="apple" Text="Apple" Group="Fruit"></asp:ListItem>
<asp:ListItem Value="banana" Text="Banana" Group="Fruit"></asp:ListItem>
<asp:ListItem Value="asparagus" Text="Asparagus" Group="Vegetable"></asp:ListItem>
<asp:ListItem Value="eggs" Text="Eggs" Group="Dairy"></asp:ListItem>
This produced the same markup as the accepted answer here but this didn't give me the postback error. I hope this saves someone some grief.
这产生了与这里接受的答案相同的标记,但是这并没有给我回发错误。我希望这能减轻一些人的痛苦。
#4
2
----- in .cs -----
List<SelectListItem> sl = new List<SelectListItem>();
sl.Add(new SelectListItem() { Text = "My text", Value = "1", Group = new SelectListGroup() { Name = "First Group" } });
sl.Add(new SelectListItem() { Text = "My text 2", Value = "2", Group = new SelectListGroup() { Name = "First Group" } });
var sl1 = new SelectList(sl,"Value","Text","Group.Name",-1);
ViewData["MyList"] = sl1;
----- in .cshtml -----
Html.DropDownList("My List", ViewData["MyList"] as SelectList,
"-- No Preference --",
new {
@class = "ui-widget ui-corner-all square_corners searchPageDropdown"
}))
#5
2
1) Add the dropdownlist adapter class from here to your project
1)将dropdownlist适配器类从这里添加到项目中
2) Add App_Browsers folder to your project(right click on project => Add => Add ASP.NET folder => App_Browsers)
2)向项目中添加app_browser文件夹(右键单击project => Add => Add ASP)。净= > App_Browsers文件夹)
3) Add a browser file into App_Browsers page and add the following code below inside browsers tag.
3)将浏览器文件添加到app_browser页面,并在浏览器标签内添加以下代码。
<browser refID="WebKit"> <controlAdapters> <adapter controlType="System.Web.UI.WebControls.DropDownList" adapterType="YourAdapterClasse'sNameSPace.DropDownListAdapter" /> </controlAdapters> </browser>
<浏览器refid="webkit">
refId = WebKit supports chrome and safari browsers
WebKit支持chrome和safari浏览器
4) Then you can add items to your dropdownlist ListItem item1 = new ListItem("Smith Street", "1"); item1.Attributes["OptionGroup"] = "Darwin";
4)然后你可以将物品添加到你的下拉列表ListItem item1 = new ListItem(“Smith Street”,“1”);item1。[" OptionGroup "]=属性“达尔文”;
ListItem item2 = new ListItem("Mitchel Street", "1");
item2.Attributes["OptionGroup"] = "Darwin";
ListItem item3 = new ListItem("Hunter Street", "2");
item3.Attributes["OptionGroup"] = "Sydney";
ListItem item4 = new ListItem("BroadwaY", "4");
item4.Attributes["OptionGroup"] = "Sydney";
venuedropdown.Items.Add(item1);
venuedropdown.Items.Add(item2);
venuedropdown.Items.Add(item3);
venuedropdown.Items.Add(item4);
#6
0
I use this method, which avoids ViewBag and ViewData:
我使用这种方法,避免了ViewBag和ViewData:
View model:
视图模型:
public class PageViewModel
{
public int SelectedDropdownItem { get; set; }
public IEnumerable<SelectListItem> DropdownList { get; set; }
}
Example entity model (for this example):
实体模型示例(本例中):
public class Users
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsAdministrator { get; set; }
public bool IsDefault { get; set; }
}
Controller:
控制器:
// Get list for the dropdown (this uses db values)
var userList = db.Users.ToList();
// Define the Groups
var group1 = new SelectListGroup { Name = "Administrators" };
var group2 = new SelectListGroup { Name = "Users" };
// Note - the -1 is needed at the end of this - pre-selected value is determined further down
// Note .OrderBy() determines the order in which the groups are displayed in the dropdown
var dropdownList = new SelectList(userList.Select(item => new SelectListItem
{
Text = item.Name,
Value = item.Id,
// Assign the Group to the item by some appropriate selection method
Group = item.IsAdministrator ? group1 : group2
}).OrderBy(a => a.Group.Name).ToList(), "Value", "Text", "Group.Name", -1);
// Assign values to ViewModel
var viewModel = new PageViewModel
{
// Assign the pre-selected dropdown value by appropriate selction method (if needed)
SelectedDropdownItem = userList.FirstOrDefault(a => a.IsDefault).Id,
DropdownList = dropdownList
};
View:
观点:
<!-- If needed, change 'null' to "Please select item" -->
@Html.DropDownListFor(a => a.SelectedDropdownItem, Model.DropdownList, null, new { @class = "some-class" })
Hope this helps someone to avoid what happened to me - way too much time spent finding a strongly-typed method.
希望这能帮助别人避免发生在我身上的事情——花费太多的时间去寻找一个强类型的方法。
#7
0
this little improvement to the client side of mhu's excellent solution also works if there are more than one select tags.
对于mhu优秀解决方案的客户端,如果有多个选择标记,这个小小的改进也可以工作。
With his version, indeed, each select tag gets filled with one copy of each option tag of each select tag
实际上,在他的版本中,每个select标记都包含每个select标记的每个选项标记的一个副本
(in this example, .select2 is the class in common to all the select tags)
(在本例中,.select2是所有select标记的公共类)
function filterUserGroups()
{
var groups = {};
$("select option[data-category]").each(function () {
var sGroup = $.trim($(this).attr("data-category"));
groups[sGroup] = true;
});
$.each(groups, function (c) {
$(".select2").each(function () {
$(this).find("option[data-category='" + c + "']").wrapAll('<optgroup label="' + c + '">');
})
});
}
#8
0
Here's what I did, with jquery-only, no server side changes:
以下是我所做的,仅使用jquery,没有服务器端更改:
/* Add Option Groups to Note Dropdown */
var $select = $('#<%= DropDownListIDHere.ClientID %>');
var optGroup;
$('#<%= DropDownListIDHere.ClientID %> option').each(function () {
if ($(this).val() == '<') {
/* Opener */
optGroup = $('<optGroup>').attr('label', $(this).text());
} else if ($(this).val() == '>') {
/* Closer */
$('</optGroup>').appendTo(optGroup);
optGroup.appendTo($select);
optGroup = null;
} else {
/* Normal Item */
if (optGroup) {
$('<option>' + $(this).text() + '</option>').attr('value', $(this).val()).appendTo(optGroup);
} else {
$('<option>' + $(this).text() + '</option>').attr('value', $(this).val()).appendTo($select);
}
}
$(this).remove();
});
Then, you just add specific items as openers and closers with value < and > like so:
然后,您只需添加特定的项目作为openers和closers,值为<,>为:
<asp:ListItem Text="Group 1" Value="<" />
<asp:ListItem Text="Thing 1" Value="1111" />
<asp:ListItem Text="Thing 2" Value="2222" />
<asp:ListItem Text="Thing 3" Value="3333" />
<asp:ListItem Text="Group 1" Value=">" />
Super simple, no new controls needed, only targets the select you want to change, and doesn't require every item to be in an optgroup.
超级简单,不需要新的控件,只针对您想要更改的选择,并且不要求每个项都位于optgroup中。
#9
0
I prefered a client script solution to avoid the complications at postback, so i solved it like this. Here I use an ordinary html select just to show it in function, but it works with ASP DropDownList too:
我更喜欢客户端脚本解决方案,以避免在回发时出现复杂情况,所以我这样解决了它。在这里,我使用一个普通的html选择,只是在函数中显示它,但它也适用于ASP下拉列表:
<script>
function addOptGrp() {
var t, p
for (var i = 0; i < arguments.length; i=i+2) {
t=arguments[i];
p=arguments[i+1]-i/2;
var scripts = document.getElementsByTagName('script');
/* On the next line scripts[scripts.length - 1] is the last script
in the page, which by definition will always be the calling script,
no matter how many such scripts you have */
var ddl = scripts[scripts.length - 1].previousElementSibling;
var og = document.createElement("optgroup");
og.label = t;
ddl.add(og,p);
ddl.selectedIndex = ddl.selectedIndex // needed for UI;
}
}
</script>
<select style="width:100px;">
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
<!-- here I just add the option groups in a script that immediately executes.
Notice that the script must follow immediately after the select (or DropDownList) -->
<script>addOptGrp(
'Simple fruits', 0,
'Very exotic fruits', 3
)</script>
<br><br>
<!-- Here comes another one -->
<select style="width:100px;">
<option>Red</option>
<option>Blue</option>
<option>Yellow</option>
<option>Green</option>
<option>Magenta</option>
<option>White</option>
</select>
<script>addOptGrp(
'Some colors', 0,
'Some more colors', 4
)</script>
This function fulfilled the needs I had today. Another day one might need to use a modified version, for example where it converts ordinary options to optgroups, depending on some prefix or so.
这个功能满足了我今天的需要。另一天,您可能需要使用一个修改后的版本,例如,它根据前缀将普通选项转换为optgroups。
#1
35
Check out this article, I too had need for Group DropDown list . . .
看看这篇文章,我也需要组下拉列表…
ASP.NET DropDownList with OptionGroup support
ASP。NET下拉列表与OptionGroup支持
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);
}
#2
31
I really like this client-side solution (doesn't need a custom DropDownList, but uses jQuery):
我非常喜欢这个客户端解决方案(不需要自定义的DropDownList,但使用jQuery):
backend
后端
private void _addSelectItem(DropDownList list, string title, string value, string group = null) {
ListItem item = new ListItem(title, value);
if (!String.IsNullOrEmpty(group))
{
item.Attributes["data-category"] = group;
}
list.Items.Add(item);
}
...
_addSelectItem(dropDown, "Option 1", "1");
_addSelectItem(dropDown, "Option 2", "2", "Category");
_addSelectItem(dropDown, "Option 3", "3", "Category");
...
client
客户端
var groups = {};
$("select option[data-category]").each(function () {
groups[$.trim($(this).attr("data-category"))] = true;
});
$.each(groups, function (c) {
$("select option[data-category='"+c+"']").wrapAll('<optgroup label="' + c + '">');
});
#3
4
This is old but since I used the accepted answer recently I wanted to share my experience with it. While it does provide the correct markup, it caused problems for me, specifically whenever I tried to submit a form with any dropdownlist I would get the dreaded "Invalid postback or callback argument" error. After googling like a maniac, I came across this article which then links to this blog post. The code I ended up using was this:
这是旧的,但由于我最近使用了公认的答案,我想与它分享我的经验。虽然它确实提供了正确的标记,但它给我带来了问题,特别是每当我试图提交带有任何下拉列表的表单时,我都会遇到可怕的“无效回发或回调参数”错误。在像疯子一样谷歌之后,我发现了这篇文章,然后链接到这篇博文。我最后使用的代码是:
public class DropDownListAdapter : System.Web.UI.WebControls.Adapters.WebControlAdapter {
protected override void RenderContents(HtmlTextWriter writer) {
var dropDownList = (DropDownList)Control;
var items = dropDownList.Items;
var groups = (from p in items.OfType<ListItem>()
group p by p.Attributes["Group"] into g
select new { Label = g.Key, Items = g.ToList() });
foreach (var group in groups)
{
if (!String.IsNullOrEmpty(group.Label))
{
writer.WriteBeginTag("optgroup");
writer.WriteAttribute("label", group.Label);
writer.Write(">");
}
var count = group.Items.Count();
if (count > 0)
{
var flag = false;
for (var i = 0; i < count; i++)
{
var item = group.Items[i];
writer.WriteBeginTag("option");
if (item.Selected)
{
if (flag)
{
throw new HttpException("Multiple selected items not allowed");
}
flag = true;
writer.WriteAttribute("selected", "selected");
}
if (!item.Enabled)
{
writer.WriteAttribute("disabled", "true");
}
writer.WriteAttribute("value", item.Value, true);
if (Page != null)
{
Page.ClientScript.RegisterForEventValidation(dropDownList.UniqueID, item.Value);
}
writer.Write('>');
HttpUtility.HtmlEncode(item.Text, writer);
writer.WriteEndTag("option");
writer.WriteLine();
}
}
if (!String.IsNullOrEmpty(group.Label))
{
writer.WriteEndTag("optgroup");
}
}
}
}
The listitems used here are created in the design page rather than the code-behind page like so:
这里使用的listitems是在设计页面中创建的,而不是像这样的代码隐藏页面:
<asp:ListItem Value="apple" Text="Apple" Group="Fruit"></asp:ListItem>
<asp:ListItem Value="banana" Text="Banana" Group="Fruit"></asp:ListItem>
<asp:ListItem Value="asparagus" Text="Asparagus" Group="Vegetable"></asp:ListItem>
<asp:ListItem Value="eggs" Text="Eggs" Group="Dairy"></asp:ListItem>
This produced the same markup as the accepted answer here but this didn't give me the postback error. I hope this saves someone some grief.
这产生了与这里接受的答案相同的标记,但是这并没有给我回发错误。我希望这能减轻一些人的痛苦。
#4
2
----- in .cs -----
List<SelectListItem> sl = new List<SelectListItem>();
sl.Add(new SelectListItem() { Text = "My text", Value = "1", Group = new SelectListGroup() { Name = "First Group" } });
sl.Add(new SelectListItem() { Text = "My text 2", Value = "2", Group = new SelectListGroup() { Name = "First Group" } });
var sl1 = new SelectList(sl,"Value","Text","Group.Name",-1);
ViewData["MyList"] = sl1;
----- in .cshtml -----
Html.DropDownList("My List", ViewData["MyList"] as SelectList,
"-- No Preference --",
new {
@class = "ui-widget ui-corner-all square_corners searchPageDropdown"
}))
#5
2
1) Add the dropdownlist adapter class from here to your project
1)将dropdownlist适配器类从这里添加到项目中
2) Add App_Browsers folder to your project(right click on project => Add => Add ASP.NET folder => App_Browsers)
2)向项目中添加app_browser文件夹(右键单击project => Add => Add ASP)。净= > App_Browsers文件夹)
3) Add a browser file into App_Browsers page and add the following code below inside browsers tag.
3)将浏览器文件添加到app_browser页面,并在浏览器标签内添加以下代码。
<browser refID="WebKit"> <controlAdapters> <adapter controlType="System.Web.UI.WebControls.DropDownList" adapterType="YourAdapterClasse'sNameSPace.DropDownListAdapter" /> </controlAdapters> </browser>
<浏览器refid="webkit">
refId = WebKit supports chrome and safari browsers
WebKit支持chrome和safari浏览器
4) Then you can add items to your dropdownlist ListItem item1 = new ListItem("Smith Street", "1"); item1.Attributes["OptionGroup"] = "Darwin";
4)然后你可以将物品添加到你的下拉列表ListItem item1 = new ListItem(“Smith Street”,“1”);item1。[" OptionGroup "]=属性“达尔文”;
ListItem item2 = new ListItem("Mitchel Street", "1");
item2.Attributes["OptionGroup"] = "Darwin";
ListItem item3 = new ListItem("Hunter Street", "2");
item3.Attributes["OptionGroup"] = "Sydney";
ListItem item4 = new ListItem("BroadwaY", "4");
item4.Attributes["OptionGroup"] = "Sydney";
venuedropdown.Items.Add(item1);
venuedropdown.Items.Add(item2);
venuedropdown.Items.Add(item3);
venuedropdown.Items.Add(item4);
#6
0
I use this method, which avoids ViewBag and ViewData:
我使用这种方法,避免了ViewBag和ViewData:
View model:
视图模型:
public class PageViewModel
{
public int SelectedDropdownItem { get; set; }
public IEnumerable<SelectListItem> DropdownList { get; set; }
}
Example entity model (for this example):
实体模型示例(本例中):
public class Users
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsAdministrator { get; set; }
public bool IsDefault { get; set; }
}
Controller:
控制器:
// Get list for the dropdown (this uses db values)
var userList = db.Users.ToList();
// Define the Groups
var group1 = new SelectListGroup { Name = "Administrators" };
var group2 = new SelectListGroup { Name = "Users" };
// Note - the -1 is needed at the end of this - pre-selected value is determined further down
// Note .OrderBy() determines the order in which the groups are displayed in the dropdown
var dropdownList = new SelectList(userList.Select(item => new SelectListItem
{
Text = item.Name,
Value = item.Id,
// Assign the Group to the item by some appropriate selection method
Group = item.IsAdministrator ? group1 : group2
}).OrderBy(a => a.Group.Name).ToList(), "Value", "Text", "Group.Name", -1);
// Assign values to ViewModel
var viewModel = new PageViewModel
{
// Assign the pre-selected dropdown value by appropriate selction method (if needed)
SelectedDropdownItem = userList.FirstOrDefault(a => a.IsDefault).Id,
DropdownList = dropdownList
};
View:
观点:
<!-- If needed, change 'null' to "Please select item" -->
@Html.DropDownListFor(a => a.SelectedDropdownItem, Model.DropdownList, null, new { @class = "some-class" })
Hope this helps someone to avoid what happened to me - way too much time spent finding a strongly-typed method.
希望这能帮助别人避免发生在我身上的事情——花费太多的时间去寻找一个强类型的方法。
#7
0
this little improvement to the client side of mhu's excellent solution also works if there are more than one select tags.
对于mhu优秀解决方案的客户端,如果有多个选择标记,这个小小的改进也可以工作。
With his version, indeed, each select tag gets filled with one copy of each option tag of each select tag
实际上,在他的版本中,每个select标记都包含每个select标记的每个选项标记的一个副本
(in this example, .select2 is the class in common to all the select tags)
(在本例中,.select2是所有select标记的公共类)
function filterUserGroups()
{
var groups = {};
$("select option[data-category]").each(function () {
var sGroup = $.trim($(this).attr("data-category"));
groups[sGroup] = true;
});
$.each(groups, function (c) {
$(".select2").each(function () {
$(this).find("option[data-category='" + c + "']").wrapAll('<optgroup label="' + c + '">');
})
});
}
#8
0
Here's what I did, with jquery-only, no server side changes:
以下是我所做的,仅使用jquery,没有服务器端更改:
/* Add Option Groups to Note Dropdown */
var $select = $('#<%= DropDownListIDHere.ClientID %>');
var optGroup;
$('#<%= DropDownListIDHere.ClientID %> option').each(function () {
if ($(this).val() == '<') {
/* Opener */
optGroup = $('<optGroup>').attr('label', $(this).text());
} else if ($(this).val() == '>') {
/* Closer */
$('</optGroup>').appendTo(optGroup);
optGroup.appendTo($select);
optGroup = null;
} else {
/* Normal Item */
if (optGroup) {
$('<option>' + $(this).text() + '</option>').attr('value', $(this).val()).appendTo(optGroup);
} else {
$('<option>' + $(this).text() + '</option>').attr('value', $(this).val()).appendTo($select);
}
}
$(this).remove();
});
Then, you just add specific items as openers and closers with value < and > like so:
然后,您只需添加特定的项目作为openers和closers,值为<,>为:
<asp:ListItem Text="Group 1" Value="<" />
<asp:ListItem Text="Thing 1" Value="1111" />
<asp:ListItem Text="Thing 2" Value="2222" />
<asp:ListItem Text="Thing 3" Value="3333" />
<asp:ListItem Text="Group 1" Value=">" />
Super simple, no new controls needed, only targets the select you want to change, and doesn't require every item to be in an optgroup.
超级简单,不需要新的控件,只针对您想要更改的选择,并且不要求每个项都位于optgroup中。
#9
0
I prefered a client script solution to avoid the complications at postback, so i solved it like this. Here I use an ordinary html select just to show it in function, but it works with ASP DropDownList too:
我更喜欢客户端脚本解决方案,以避免在回发时出现复杂情况,所以我这样解决了它。在这里,我使用一个普通的html选择,只是在函数中显示它,但它也适用于ASP下拉列表:
<script>
function addOptGrp() {
var t, p
for (var i = 0; i < arguments.length; i=i+2) {
t=arguments[i];
p=arguments[i+1]-i/2;
var scripts = document.getElementsByTagName('script');
/* On the next line scripts[scripts.length - 1] is the last script
in the page, which by definition will always be the calling script,
no matter how many such scripts you have */
var ddl = scripts[scripts.length - 1].previousElementSibling;
var og = document.createElement("optgroup");
og.label = t;
ddl.add(og,p);
ddl.selectedIndex = ddl.selectedIndex // needed for UI;
}
}
</script>
<select style="width:100px;">
<option>Apple</option>
<option>Pear</option>
<option>Banana</option>
<option>Orange</option>
</select>
<!-- here I just add the option groups in a script that immediately executes.
Notice that the script must follow immediately after the select (or DropDownList) -->
<script>addOptGrp(
'Simple fruits', 0,
'Very exotic fruits', 3
)</script>
<br><br>
<!-- Here comes another one -->
<select style="width:100px;">
<option>Red</option>
<option>Blue</option>
<option>Yellow</option>
<option>Green</option>
<option>Magenta</option>
<option>White</option>
</select>
<script>addOptGrp(
'Some colors', 0,
'Some more colors', 4
)</script>
This function fulfilled the needs I had today. Another day one might need to use a modified version, for example where it converts ordinary options to optgroups, depending on some prefix or so.
这个功能满足了我今天的需要。另一天,您可能需要使用一个修改后的版本,例如,它根据前缀将普通选项转换为optgroups。