Hopefully an easy one to answer. I am using the code below to produce a cascading dropdown, however when I select the Country, the State auto populates with the first value (for the appropriate Country) in my State table. I think that I need to add an empty string somewhere but I'm not sure where.
Thanks
h2>Cascading DropDownList Sample</h2>
<div>
<div>
@Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { @style = "width:250px;" })
</div>
<div style="margin-top:50px;">
@Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please select a state", new { @style = "width:250px;" })
</div>
</div>
@section scripts
{
<script>
$(function () {
$.ajax({
type: "GET",
url: "/test/getcountries",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCountry').append('<option value="' + value.CountryId + '">' + value.CountryName +'</option>');
});
}
});
$('#dropdownCountry').change(function () {
$('#dropdownState').empty();
$.ajax({
type: "POST",
url: "/test/GetStatesByCountryId",
datatype: "Json",
data: { countryId: $('#dropdownCountry').val() },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownState').append('<option value ="' + value.Id + '">' + value.StateName + '</option>');
});
}
});
});
});
</script>
}
答案 0 :(得分:0)
You can just add a mock item in the first place of the elements returned by the service GetStatesByCountryId. The id field can be blank and the statename can be something like "Please Choose". Then, you can check if the selected item id is blank or not.
答案 1 :(得分:0)
在您的国家/地区下拉更改活动成功回拨功能,您必须进行一行更改。
$('#dropdownState').append('<option>Select State</option>');
$.each(data, function (index, value) {
$('#dropdownState').append('<option value ="' +
value.Id + '">' + value.StateName + '</option>');
});
我建议你把你的选项放在变量中,最后将该值分配给下拉。
var html = '';
html = '<option>Select State</option>';
$.each(data, function (index, value) {
html += '<option value ="' +
value.Id + '">' + value.StateName + '</option>';
});
$('#dropdownState').html(html)
追加函数添加选项以选择会导致问题的元素,如果您选择将提供5个状态的国家/地区。然后你选择提供10个状态的国家B然后最终结果状态下拉将是国家B的15个状态选项。因此,我没有使用html函数来代替追加。