好的,首先呈现状态(我假设您已经为您的视图模型提供了状态列表):
<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);
}
}
}