まず最初に、レンダリング状態を確認します (ビュー モデルで状態のリストを提供したと仮定します):
<select id="stateList">
<option value="0">-------- select state ------ </option>
@foreach(var state in Model.States)
{
<option value="@state.Id">
@state.Name
</option>
}
</select>
<div id="cityContainer">
</div>
<input type="button" id="submitChanges">
Change イベントを処理して都市のリストを取得する場合:
$("#stateList").change(function(){
var id = $("option:selected",$(this)).attr("Id");
$.ajax({
url:'@Url.Action("getStateCities","YourController")'
data = {stateId = id},
success:function(data){
$.each(cities, function () {
var $cityList = $("#cityContainer");
var $checkbox= $("<input type='checkbox'></input>").attr("value",this.Id).text(this.CityName);
if (this.isInState)
{
$checkbox.attr("checke","checked");
}
$checkbox.appendTo($cityList);
});
}
})
});
コントローラーのアクションは次のようになります。
public JsonResult getStateCities(int stateId)
{
var data = _addressService.GetStateCities(Id).Select(c => new { c.CityName, c.Id , isInState = isCityInEstate(cityId)});
return new JsonResult { Data = data };
}
実装はあなた次第です.今GetStateCities
、isCityInEstate
フォームデータをコントローラーに送り返します:
$("#submitChanges").click(function(){
var citiesToSubmit = [];
$("input[type=checkbox]",$("#cityContainer")).each(function(){
var include = $(this).prop('checked'),
cityId = $(this).attr("Id");
citiesToSubmit.push({CityId:cityId, Include : include});
});
$.ajax({
url:'@Url.Action("SubmitCities","YourController")',
data :{StateId = $("#estateList").attr("Id") , Cities : citiesToSubmit}
success:function(){
alert('cities submitted');
}
});
});
そして最後にコントローラー:
public class SubmitedCityViewModel
{
public int StateId {get;set;}
public List<CityViewModel> Cities {get;set;}
}
public class CityViewModel
{
public int cityId {get;set;}
public bool Include {get;set;}
}
public JsonResult SubmitCities(SubmitedCityViewModel model){
foreach(var city in model.Cities)
{
if (city.Inclue)
{
//update db to include
_addressService.AddCityToState(city.Id,model.StateId);
}
else
{
//update db to remove
_addressService.RemoveCityFromState(city.Id,model.StateId);
}
}
}