9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ASP.NET MVC 5.2でひっそりとoptgroupがサポートされている

Posted at

ASP.NET MVCのDropDownListForはoptgoupがサポートされていなくて残念な思いをしていましたが、5.2でひっそりとサポートされるようになりました。

新しいヘルパが増えるのではなく、System.Web.Mvc.SelectListItemクラスにGroupというプロパティが追加されていて、このプロパティにSystem.Web.Mvc.SelectListGroupオブジェクトを設定します。同じオブジェクトが設定されているSelectListItemがoptgroupとしてグルーピングされるという仕組みです。名前が同じだけではグルーピングされません。

var items = new List<SelectListItem>();

var group1 = new SelectListGroup() { Name = "Group 1" };
var group1_2 = new SelectListGroup() { Name = "Group 1" };
var group2 = new SelectListGroup() { Name = "Group 2" };

items.Add(new SelectListItem() { Text = "Item1", Group = group1 });
items.Add(new SelectListItem() { Text = "Item2", Group = group1 });
items.Add(new SelectListItem() { Text = "Item3", Group = group1_2 }); // 別のグループになる
items.Add(new SelectListItem() { Text = "Item4", Group = group2 });
items.Add(new SelectListItem() { Text = "Item5", Group = group2 });
items.Add(new SelectListItem() { Text = "Item6", Group = group1 }); // 初めのgroup1と一緒になる
items.Add(new SelectListItem() { Text = "Item7", Group = group1 }); // 初めのgroup1と一緒になる
@Html.DropDownList("select", items)

screenshot.png

参考

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?