- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- ソース を表示
- dotNet-ASP.NET MVC/Razor/チェックボックス CheckBoxListForプラグイン へ行く。
- 1 (2014-02-27 (木) 19:01:10)
- 2 (2014-02-27 (木) 20:39:49)
CheckBoxListForプラグイン
使い方
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()を使用する。
使い方の補足
上の使い方のサンプルで出力されるチェックボックスリストの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()
@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()へ渡す為の値をセットアップする
/// <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;
}