我在html中有2个Dropdownlist,国家/地区的dropdownlist和州下拉列表。我使用MVC,我希望成为这样的输出,如果我更改选定的国家/地区,所选国家/地区的状态将填入下拉列表状态。我从数据库获取国家和州的数据,在州表中有countryId的字段。感谢帮助。
这是Html中的示例代码。
<div class="fieldBlock">
<div><label>Country</label> *</div>
<div>@Html.DropDownListFor(model => model.Country.Id, Model.CountrySelectList, new { @class = "width305", @id = "ddlCountry" })</div>
@Html.HiddenFor(model => model.Country.Name) @Html.HiddenFor(model => model.Country.Abbreviation)
<div>@Html.ValidationMessageFor(model => model.Employee.StateId)</div>
</div>
<div class="fieldBlock">
<div>@Html.LabelFor(model => model.Employee.StateId, "State/Province") *</div>
<div>@Html.DropDownListFor(model => model.Employee.StateId, Model.CountryStateProvinceSelectList, new { @class = "width305" })</div>
<div>@Html.ValidationMessageFor(model => model.Employee.StateId)</div>
</div>
答案 0 :(得分:3)
试试这个
在视图中
<script type="text/javascript">
$(function() {
$("#ddlCountry").change(function() {
var selectedItem = $(this).val();
var ddlStates = $("#ddlState");
var statesProgress = $("#states-loading-progress");
statesProgress.show();
$.ajax({
cache: false,
type: "GET",
url: "@(Url.Action("SomeAction", "SomeController"))",
data: { "countryId": selectedItem},
success: function (data) {
ddlStates.html('');
$.each(data, function(id, option) {
ddlStates.append($('<option></option>').val(option.id).html(option.name));
});
},
error:function (xhr, ajaxOptions, thrownError){
alert('Failed to retrieve states.');
}
});
});
});
</script>
<div class="fieldBlock">
<div><label>Country</label> *</div>
<div>@Html.DropDownListFor(model => model.Country.Id, Model.CountrySelectList, new { @class = "width305", @id = "ddlCountry" })</div>
@Html.HiddenFor(model => model.Country.Name) @Html.HiddenFor(model => model.Country.Abbreviation)
<div>@Html.ValidationMessageFor(model => model.Employee.StateId)</div>
</div>
<div class="fieldBlock">
<div>@Html.LabelFor(model => model.Employee.StateId, "State/Province") *</div>
<div>@Html.DropDownListFor(model => model.Employee.StateId, Model.CountryStateProvinceSelectList, new { @class = "width305", @id = "ddlState" })</div>
<div>@Html.ValidationMessageFor(model => model.Employee.StateId)</div>
</div>
在控制器
中public ActionResult SomeAction(string countryId)
{
//perform your action here
var states = _stateProvinceService.GetStateProvincesByCountryId(country.Id).ToList();
var result = (from s in states
select new { id = s.Id, name = s.GetLocalized(x => x.Name) }
).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
注意:检查Id
是否正确绑定到下拉列表,并且我已经编写了虚拟代码以获取状态。