* CheckBoxListForプラグイン [#ub602afb]
** 使い方 [#r2e257d9]
http://www.codeproject.com/Tips/613785/How-to-Use-CheckBoxListFor-With-ASP-NET-MVC-4
+ チェックボックスを表すモデルクラスを作る。
+ そのモデルクラスのリスト(配列)を全選択肢のリスト(AvailableFruits)とチェック済みの選択肢のリスト(SelectedFruits)としてViewModelのフィールドに置く。
+ ユーザが選択した選択肢を格納するモデルクラス(PostedFruits)を作る。
+ コントローラーで、PostedFruitsの受け取り処理、DB等からのAvailableFruitsの生成処理、PostedFruitsとAvailableFruitsからSelectedFruitsを確定する処理、を行う。
+ ビューでCheckBoxListFor()を使用する。
** 使い方の補足 [#tba53b39]
*** 上の使い方のサンプルで出力されるチェックボックスリストのHTML [#i88c94e6]
#sh(html){{
<input id="PostedFruits_FruitIds14" name="PostedFruits.FruitIds" type="checkbox" value="1"></input>
<label for="PostedFruits_FruitIds14">Apple</label>
<input id="PostedFruits_FruitIds15" name="PostedFruits.FruitIds" type="checkbox" value="2"></input>
<label for="PostedFruits_FruitIds15">Banana</label>
<input id="PostedFruits_FruitIds16" name="PostedFruits.FruitIds" type="checkbox" value="3"></input>
<label for="PostedFruits_FruitIds16">Cherry</label>
}}
*** CheckBoxListFor() [#jf2aa4ff]
@Html.CheckBoxListFor(model => model.PostedFruits.FruitIds, // (1)
model => model.AvailableFruits, // (2)
fruit => fruit.Id, // (3)
fruit => fruit.Name, // (4)
model => model.SelectedFruits, // (5)
Position.Horizontal)
- (1) この指定により、INPUTタグのNAME属性が<input name="PostedFruits.FruitsIds">のようになり、Controllerで以下のように配列postedFruitsとして参照できる。
public ActionResult Index(FruitViewModel vm) { var postedFruits = vm.PostedFruits; }
public ActionResult Index(PostedFruits postedFruits) {}
- (2) チェックボックスの全ての選択肢
- (3) INPUTタグのVALUE属性
- (4) INPUTタグの隣に表示されるLABELタグの文字
- (5) ユーザが選択した値 (List<Fruit>)
-- なお、PostedFruitsはユーザが選択した値、SeelctedFruitsはユーザが選択した中で全選択肢に含まれる値を表す
*** コントローラーでユーザ入力値postedFruitsからCheckBoxListFor()へ渡す為の値をセットアップする [#q19ba925]
/// <summary>
/// for setup view model, after post the user selected fruits data
/// </summary>
private FruitViewModel GetFruitsModel(PostedFruits postedFruits)
{
// setup properties
var model = new FruitViewModel();
var selectedFruits = new List<Fruit>();
var postedFruitIds = new string[0];
if (postedFruits == null) postedFruits = new PostedFruits();
// if a view model array of posted fruits ids exists
// and is not empty,save selected ids
if (postedFruits.FruitIds != null && postedFruits.FruitIds.Any()) {
postedFruitIds = postedFruits.FruitIds;
}
// if there are any selected ids saved, create a list of fruits
if (postedFruitIds.Any()) {
selectedFruits = FruitRepository.GetAll()
.Where(x => postedFruitIds.Any(s => x.Id.ToString().Equals(s)))
.ToList();
}
//setup a view model
model.AvailableFruits = FruitRepository.GetAll().ToList();
model.SelectedFruits = selectedFruits;
model.PostedFruits = postedFruits;
return model;
}
** チェックボックスリストをテーブルタグで整形する [#dc333100]
http://www.jjask.com/261808/mvc-4-razor-checkboxlistfor-formatting-issue
** 参考 [#a5d53bcd]
- Nuget https://www.nuget.org/packages/MvcCheckBoxList
- Project http://mvccbl.com/
- Code Project http://www.codeproject.com/Articles/292050/CheckBoxList-For-a-missing-MVC-extension