ドロップダウンリスト
2016/10/04
まずはシンプルに1段のみ

カテゴリー用のモデル
public class Category
{
public string Id { get; set; }
public string Name { get; set; }
}
カテゴリー一覧を返すサービス
public static List<Category> GetCategory()
{
return new List<Category> {
new Category{Id = "001", Name = "果物"},
new Category{Id = "002", Name = "野菜"}
};
}
ViewModel
選択肢(オプション)の配列をViewにどうやって渡すかViewBagを使うか、ViewModelに入れるか悩みますが、今回はDBアクセスないのでセットし忘れが無いViewModelのコンストラクタで。
public class DDLViewModel
{
public DDLViewModel()
{
//// ListデータをSelectListItemに詰め替え
//// こんな回りくどいことをしなくてももっとエレガントな方法あるかも
//this.CategoryList = GoodsService.GetCategory().Select(c => new SelectListItem
//{
// Text = c.Name,
// Value = c.Id
//}).OrderByDescending(s => s.Value); // ここで並べ替えることはまずないでしょうが、必要な時のため
// ありました。こちらの方がエレガントです
// https://code.msdn.microsoft.com/Cascading-DropDownList-in-833683f9
// SelectListにはOrderByが無い様なので場所を移動しました
// SortのキーもValueからIdに変更
this.CategoryList = new SelectList(WorkerService.GoodsService.GetCategory().OrderByDescending(c => c.Id).ToArray(),
"Id",
"Name");
}
[Display(Name = "分類")]
[Required]
public string SelectCategoryId { get; set; }
//public IEnumerable<SelectListItem> CategoryList { get; set; }
//正しくはSelectListを使うようなので
public SelectList CategoryList { get; set; }
}
View
@model Sample.Models.DDLViewModel
@{
ViewBag.Title = "Index";
}
<h2>ドロップダウンリスト</h2>
<div>
@using (Html.BeginForm())
{
<div class="form-group">
<div>@Html.LabelFor(m => m.SelectCategoryId)</div>
@Html.DropDownListFor(m => m.SelectCategoryId, Model.CategoryList, "選択してください", new { @class = "form-control" })
</div>
<div>
<input type="submit" value="送信" class="btn btn-primary" />
</div>
}
</div>
実行結果
コードが大きい野菜が上になっています。