我有两个用于国家和地区控制的dropdoenlist所以我想根据选定的国家绑定城市下拉列表。我怎样才能做到这一点?
这是我的代码
AirportController.cs
// GET: Airport/Create
public ActionResult Create()
{
List<City> lstCity = new DACity().GetListAll();
ViewBag.City = lstCity;
List<Country> lstCountry = new DACountry().GetListAll();
ViewBag.Country = lstCountry;
return View();
}
Create.cshtml
<div class="form-group">
@Html.LabelFor(model => model.CountryID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.CountryID, new SelectList(ViewBag.Country, "CountryID", "CountryName"), "--select--", new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CountryID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CityID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.CityID, new SelectList(ViewBag.City, "CityID", "CityName"), "--select--", new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CityID, "", new { @class = "text-danger" })
</div>
</div>
答案 0 :(得分:0)
您是否考虑过在国家/地区下拉列表中添加客户端更改事件?根据所做的选择,您可以对辅助控制器方法进行AJAX调用,然后返回一个城市列表以填充到下拉列表中。
您可能还需要考虑POST,以便在遇到任何错误时,您将在返回View之前加载城市信息,只需确保在任何服务器端验证失败时保留模型的状态。
答案 1 :(得分:0)
捕获dropdownlistfor的Onchange事件,并将所选的dropdownlistfor值传递给处理函数。
@Html.DropDownListFor(model => model.CountryID, new SelectList(ViewBag.Country, "CountryID", "CountryName"), "--select--", new { htmlAttributes = new { @class = "form-control", onchange = "ChangeCityValues(this.value)" } })
在函数内部向控制器发送ajax帖子以更改城市的模型数据源并将值传递给它
$.ajax({
type: "POST",
url: '@Url.Action("ChangeCitySource", "YourControllerName")',
data: JSON.stringify({ countryId: CountryIdValueReceivedfromDropdown }),
dataType: "json",
success: function (msg) {
if (true) {
Update city dropdown
}
else {
No action
}
},
error: function () {
return "error";
}
});
在YourControllerName
控制器中:
public JsonResult ChangeCitySource( string countryId)
{
// Update city source here and return some result to ajax post
}