画面のビューモデルをいくつか作成しましょう。ユーザーがドロップダウンから州を選択する必要がある店舗検索ビューを実行していると仮定すると、その州に属する店舗がラジオ ボタンに表示されます。
public class LocateStore
{
public List<SelectListItem> States { set;get;}
public int SelectedState { set;get;}
public LocateStore()
{
States=new List<SelectListItem>();
}
}
public class StoreLocation
{
public List<Store> Stores{ set;get;}
public int SelectedStore { set;get;}
public StoreLocation()
{
Stores=new List<Store>();
}
}
public class Store
{
public int ID { set;get;}
public string Name { set;get;}
}
アクションで、 LocateStoreGET
クラスのオブジェクトを作成し、State コレクションのプロパティ値を設定して、それをビューに送信します。
public ActionResult Locate()
{
var vm=new LocateStore();
//The below code is hardcoded for demo. you mat replace with DB data.
vm.States= new List<SelectListItem>
{
new SelectListItem { Value = 1, Text = "MI" },
new SelectListItem { Value = 2, Text = "CA" },
new SelectListItem { Value = 3, Text = "OH" }
};
return View(vm);
}
LocateStore
次に、クラスに強く型付けされた Locate ビューを作成します。ドロップダウンの変更イベントをリッスンし、ajax 呼び出しを行ってラジオ ボタン リスト ビューを取得するための JavaScript コードを用意します。
@model LocateStore
@Html.DropDownListFor(x=>x.SelectedState,
new SelectList(Model.States,"Value","Text"),"Please select")
<div id="stores">
</div>
<script type="text/javascript">
$(function(){
$("#SelectedState").change(function(){
$("#stores").load("@Url.Action("GetStores","Store")/"+$(this).val());
});
});
</script>
ここでGetStores
、選択された状態 ID を受け取り、ラジオ ボタン リスト形式の Store 名を持つ部分ビューを返すアクション メソッドが必要です。
public ActionResult GetStores(int id)
{
var vm=new StoreLocation();
//The below code is hardcoded for demo. you mat replace with DB data.
vm.Stores= new List<Store>
{
new Store{ ID= 1, Name= "Costco" },
new Store{ ID= 2, Name= "RiteAid" },
new Store{ ID= 3, Name= "Target" }
};
return PartialView(vm);
}
そして今、クラスGetStores.cshtml
に強く型付けされたこのメソッドのビューが必要ですStoreLocation
@model StoreLocation
@foreach(var item in Model.Stores)
{
@Html.RadioButtonFor(b=>b.SelectedStore,item.ID) @item.Name
}
アプリを実行すると、ユーザーがドロップダウンから項目を選択すると、ラジオ ボタンのある部分ビューが表示されます。
参考までに、上記のコードを使用した実際のサンプルを次に示します。