:このようなビューの何かを
[HttpPost]
public ActionResult GetCities(GetCitiesViewModel model)
{
var selectedState = model.ddlStates;
IEnumerable<CityViewModel> cities = GetCitiesInState(selectedState);
IEnumerable<SelectListItem> filteredItems =
cities.Select(c => new SelectListItem {Text = c.Name, Value = c.CityId.ToString()});
return PartialView("CityList", filteredItems);
}
private IEnumerable<CityViewModel> GetCitiesInState(int stateId)
{
// Just returning a list regardless of state ID. But you would look the cities up by state here.
return new List<CityViewModel>
{
new CityViewModel {CityId = 1, Name = "London"},
new CityViewModel {CityId = 2, Name = "Birmingham"},
};
}
public class CityViewModel
{
public int CityId { get; set; }
public string Name { get; set; }
}
public class GetCitiesViewModel
{
public int ddlStates { get; set; }
}
を。私は都市をJsonとして返すコントローラーアクションを使用します。私が使用しているjQueryは、州のために選択された値がないとき、都市のドロップダウンをクリアして無効にします。ここで
はここに私のマークアップ
@Html.LabelFor(model => model.StateCode)
@Html.DropDownList("StateCode", string.Empty)
@Html.LabelFor(model => model.CityID)
@Html.DropDownList("CityID", string.Empty)
であるjQueryのです
$("select#StateCode").bind('change', function() {
var StateCode = $("select#StateCode option:selected").val();
if (StateCode == "" || StateCode == 0)
{
$("select#CityID").empty();
$("select#CityID").attr('disabled', 'disabled');
}
else
{
$.getJSON('@Url.Action("GetCityiesForState")', { StateCode: StateCode }, function (data) {
$("select#CityID").empty();
$.each(data, function (i, c) {
$('select#CityID').append('<option value="' + c.Value + '">' + c.Text + '</option>');
});
$("select#CityID").removeAttr('disabled');
$("select#CityID option:first").attr('selected', 'selected');
});
}
});
コントローラーアクション
public JsonResult GetCityiesForState(string stateCode) {
var cities = repository.getCities(stateCode);
return Json(cities, JsonRequestBehavior.AllowGet);
}